Remove line breaks in Bourne Shell from variable

扶醉桌前 提交于 2019-12-09 05:11:03

问题


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?


回答1:


echo $VALUES | tr '\n' ' '




回答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



回答3:


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

echo -n $VALUES




回答4:


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'`"


来源:https://stackoverflow.com/questions/2103030/remove-line-breaks-in-bourne-shell-from-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!