2

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??

2
  • Could you indent the output parts with 4 spaces? I think you have multiline strings, while everything now is displayed on one line. The 4 spaces indentation put it in code formatting Commented Jun 11, 2010 at 6:08
  • probably using the join command, except I'd need to see how $var1 and $var2 got created. Commented Jun 11, 2010 at 6:25

5 Answers 5

2

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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

Comments

0

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.