0

I have two queries that I am running against two different systems. They each return one row, and I want to output them on a single line.

if the queries produce results similar to:

echo this that and more
echo other great news

I want to be able to do some reordering and formatting like so:

echo other this that great news and more 

If I could figure out how to echo the output of the line into multiple variables I would be good. I got this to work:

echo this that and more | while IFS=" ", read a b c
do
  echo a=$a b=$b c=$c
done 

But once I am out of the while loop the variables a b and c are out of scope and no longer have their values.

  • First off, welcome! For what it's worth, this worked fine for me under bash. – airhuff Jan 18 '17 at 22:55
  • Is the comma after IFS=" " a typo, or in your actual code? – Barmar Jan 18 '17 at 23:01
  • Well, if you want one row of data, why not pipe everything into tr -d '\n' to delete the newline character or tr '\n' ' ' to substitute with space ? – Sergiy Kolodyazhnyy Jan 18 '17 at 23:17
1

It's not that they are out of scope, ksh (at least the AT&T version) doesn't have that limitation of bash. It's that read is called twice.

The second time is the one where it fails and gets you out of the loop.

As that second read reads nothing, it sets a, b and c to the empty string.

Just do:

echo this that and more | IFS=" " read a b c
echo "a=$a b=$b c=$c"
  • Something was wrong with the way it worked, but I did get it to work. Here is my actual command: $> hive -f q1.hql | IFS=" " read var1 var2 ... var5<eol> I don't know why but it was breaking it up and putting a lot of the values in var1 and then none in var2,3,4 and then the rest in var5. I changed it to two commands $> line_x=$(hive -f q1.hql)<eol> $> echo line_x | IFS=" " read var1 var2 ... var5<eol> and this worked. – markwusinich Jan 19 '17 at 16:13
  • @markwusinich, possibly the fields were tab separated and you forgot the quotes in echo $line_x which would cause the sequences of $IFS characters to be converted to a single space (and globs expanded). If you just do hive -f -q1.hql | read var1 var2... without touching IFS, that would split on any sequence of tab and space (the default value of IFS has space tab and newline). – Stéphane Chazelas Jan 19 '17 at 16:34
0
a=$(echo this...)
b=$(echo other...)
echo -- "$a $b"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.