18

In bourne shell I have the following:

VALUES=`some command that returns multiple line values`

echo $VALUES

Looks like:

"ONE"
"TWO"
"THREE"
"FOUR"

I would like it to look like:

"ONE" "TWO" "THREE" "FOUR"

Can anyone help?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Chris Kannon
  • 5,931
  • 4
  • 25
  • 35
  • Do you want an array of 4 strings, or do you want the single string "ONE TWO THREE FOUR"? – William Pursell Jan 20 '10 at 16:36
  • nit: The command in backticks (why not use $() instead?) does not 'return' multiple values. It outputs multiple lines, and returns a single value, hopefully zero. – William Pursell Jan 20 '10 at 16:37
  • William, very simplified version. I actually take the output of the backticks, do some parse work on the data in VALUES than output VALUES later. – Chris Kannon Jan 20 '10 at 16:39

4 Answers4

47

echo $VALUES | tr '\n' ' '

eliah
  • 2,267
  • 1
  • 21
  • 23
  • 1
    Nice. Just a tweak: in bash and zsh at least you can pipe in the env var without echo with <<<, i.e. tr '\n' ' ' <<< $VALUES. – liwp Jan 20 '10 at 16:40
  • 1
    @liwp +1 for the nice tip. BTW how to pass escaped string using `<<<` i.e. `tr -d '\n' <<< "a line with line feed \n"`. the string doesn't escape '\n' in the double quote as I expected, any idea? – mko Apr 13 '13 at 05:37
  • 2
    If you don't want the spaces you can do `echo $VALUES | tr -d '\n'`, the result would be `ONETWOTHREEFOUR` – Jaime Hablutzel Aug 02 '14 at 11:08
2

Another method, if you want to not just print out your code but assign it to a variable, and not have a spurious space at the end:

$ var=$(tail -1 /etc/passwd; tail -1 /etc/passwd)
$ echo "$var"
apache:x:48:48:Apache:/var/www:/sbin/nologin
apache:x:48:48:Apache:/var/www:/sbin/nologin
$ var=$(echo $var)
$ echo "$var"     
apache:x:48:48:Apache:/var/www:/sbin/nologin apache:x:48:48:Apache:/var/www:/sbin/nologin
1

The accepted solution didn't work for me (on OS X Yosemite). This is what I used:

echo -n $VALUES

José Manuel Sánchez
  • 5,215
  • 2
  • 31
  • 24
0

Another option is using xargs (which keeps a final newline though - instead of a possible trailing space using tr):

echo $VALUES | xargs
printf '%s\n' 1 2 3 4 5 | xargs

@yozloy: how to pass escaped string using <<<

tr -d '\n' <<< "`printf '%b' 'a line with line feed \n'`"
chan
  • 1