0

I read some data out of a file, used grep for the only two columns needed, and redirected the output into a variable.

My script looks like this:

#!/bin/bash
cat hosts.cfg | grep 'address\|host_name' | sed -e 's/\<address\>//g'  | while read line; do
        echo $line | sed 's/host_name//g' | sed -r 's/\s+//g' ;
done

The output looks something like this now:

Host1
xx.xx.xx.xx
Host2
xx.xx.xx.xx

The problem is that hosts and ips must be saved into an array, not a file!

Output must look like this:

Host1(tab)xx.xx.xx.xx

Host2(tab)xx.xx.xx.xx
2
  • Output? I thought you said you want it in variable. Commented Oct 14, 2013 at 8:12
  • What does hosts.cfg look like? There may be a simpler solution than your chains of sed commands. Commented Oct 14, 2013 at 16:30

4 Answers 4

1

You are looking for process substitution. $(command), or old-style in `s.

(sorry, the description of how it should work is not clear enough for me to show modified version of your code)

Sign up to request clarification or add additional context in comments.

Comments

0

You can use awk:

echo $output | awk 'NR%2{printf $0"\t";next;}1'

To save any command output, wrap it in backticks, or the newer (but less backward compatible) $(command) style substitution. E.g.:

result=`echo $output | awk 'NR%2{printf $0"\t";next;}1'`

2 Comments

It must be saved in memory, not just printed .
My code looks like this right now: ' cat hosts.cfg | grep 'address\|host_name' | sed -e 's/\<address\>//g' | while read line; do echo $line | sed 's/host_name//g' | sed -r 's/\s+//g' | awk 'NR%2{printf $0"\t";next;}1' ; done ' It returns this: Host1 xx.xx.xx.xx Host2 xx.xx.xx.xx . What I need, to list them on single line like this: Host1 xx.xx.xx.xx (newline) Host2 xx.xx.xx.xx .
0

using sed 'N;s/\n/\t/g'

change

Host1
xx.xx.xx.xx
Host2
xx.xx.xx.xx

to

Host1(tab)xx.xx.xx.xx
Host2(tab)xx.xx.xx.xx

Comments

0

You can use "set" to get faster output

exg:

I have file best2,

 # cat best2
 Host1 xx.xx.xx.xx Host2 xx.xx.xx.xx

make a script called: tabcheck.sh

 # cat tabcheck.sh
 #!/bin/bash
 out=$(cat best2)
 set $out
 echo -e "$1\t$2\n$3\t$4"

 # ./tabcheck.sh
 Host1   xx.xx.xx.xx
 Host2   xx.xx.xx.xx

If you use shift command(Usually only nine command line arguments can be accessed using positional parameters. The shift command gives access to command line arguments greater than nine by shifting each of the arguments.) as well.

Thanks.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.