tags:

views:

128

answers:

5

I have two variables var1 and var2. The contents of each variables come from bash shell grep command.

echo $var1 prints
123 465 326 8080

echo $var2 prints
sila kiran hinal juku

Now I want to print the above into following formats in Linux bash shell

123 sila
465 kiran
326 hinal
8080 juku

So how can I print this way in bash shell??

A: 

Without a loop:

$ var1="123 465 326 8080"
$ var2="sila kiran hinal juku"
$ var1=($var1); var2=($var2)
$ saveIFS=IFS
$ IFS=$'\n'
$ paste <(echo "${a[*]}") <(echo "${b[*]}"
$ IFS=$saveIFS

With a loop (assumes that the two strings have the same number of words):

$ var1="123 465 326 8080"
$ var2="sila kiran hinal juku"
$ var2=($var2)
$ for s in $var1; do echo $s ${vars[i++]}; done
Dennis Williamson
+1  A: 

What about?

$ paste -d" " <(echo $var1 | xargs -n1) <(echo $var2 | xargs -n1)

We can even skip the echo:

$ paste -d" " <(xargs -n1 <<< $var1) <(xargs -n1 <<< $var2)
tokland
A: 

I'd store them into arrays $var1[] and $var2[] instead of a some long string and then iterate through the arrays with a loop to output it the way you want.

If you don't want ot use arrays, you could use awk and the iterator from a loop to print out the names one at a time.

SDGuero
A: 
join <(echo $var1 | sed -r  's/ +/\n/g' | cat -n) <(echo $var2 | sed -r  's/ +/\n/g' | cat -n) -o "1.2,2.2"
Aleksey Otrubennikov
A: 

Using file descriptors and a while-loop:

var1="123 465 326 8080"
var2="sila kiran hinal juku"

IFS=" " exec 7< <(printf "%s\n" $var1) 8< <(printf "%s\n" $var2)

while read -u7 f1 && read -u8 f2; do
   echo "$f1 $f2"
done
bashfu