Unix - combine all rows into a comma-separated single row

女生的网名这么多〃 提交于 2020-05-25 05:40:57

问题


I have following values in a file in separate lines:
California
New York
Washington
South Carolina
Kansas

What would be unix script to display them in a single line (as showb below)
'California', 'New York', 'Washington', 'South Carolina', 'Kansas'
[I do not want to have any intermediate file to achieve this.. just an echo code is fine]


回答1:


Use this command tr '\n' ',' < input_file

For single quotes use sed -e "s/^/'/" input_file | sed -e "s/$/'/" | tr '\n' ','

(Not tested for single/double quote escaping issues)

For variable NEW_VAR=$(echo $VAR | sed -e "s/^/'/" | sed -e "s/$/'/" | tr '\n' ',')




回答2:


You need to use awk to format the output. Does sed and awk ring a bell?

The file <test.txt>
California
New York
Washington
South Carolina
Kansas

$ grep input file | awk '{print}' ORS=', '

California, New York, Washington, South Carolina, Kansas

Then concatenate your string and look out for the proper output.

with awk you can try this

sudo awk -F'\n' '{if(NR == 1) {printf "\x27" $0 "\x27"} else {print "," "\x27" $0 "\x27"}}' test.txt

'California','New York','Washington','South Carolina','Kansas'

You can also try this

sudo awk 'BEGIN {RS=""}{gsub(/\n/,"\x27,\x27",$0); print $0}' test.txt


来源:https://stackoverflow.com/questions/38489719/unix-combine-all-rows-into-a-comma-separated-single-row

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