How to add text at the end of each line in unix

懵懂的女人 提交于 2019-11-26 15:58:51

问题


I am doing certain text processing operations and finally able to get a file something like this

india
sudan
japan
france

now I want to add a comment in the above file like in the final file it should be something like

india | COUNTRY
sudan | COUNTRY
japan | COUNTRY
france | COUNTRY

like a same comment across the whole file. How do I do this?


回答1:


There are many ways:

sed: replace $ (end of line) with the given text.

$ sed 's/$/ | COUNTRY/' file
india | COUNTRY
sudan | COUNTRY
japan | COUNTRY
france | COUNTRY

awk: print the line plus the given text.

$ awk '{print $0, "| COUNTRY"}' file
india | COUNTRY
sudan | COUNTRY
japan | COUNTRY
france | COUNTRY

Finally, in pure bash: read line by line and print it together with the given text. Note this is discouraged as explained in Why is using a shell loop to process text considered bad practice?

$ while IFS= read -r line; do echo "$line | COUNTRY"; done < file
india | COUNTRY
sudan | COUNTRY
japan | COUNTRY
france | COUNTRY



回答2:


For a more obfuscated approach:

yes '| COUNTRY' | sed $(wc -l < file)q | paste -d ' ' file -



回答3:


Another awk

awk '$0=$0" | COUNTRY"' file



回答4:


You can also use xargs with echo for this:

< file xargs -d "\n" -rI % echo '% | COUNTRY'

This will make xargs take each line of file and pass it one at a time† to the specified echo command, replacing the % (or whatever character you choose) with the input line.

† By default xargs will pass multiple lines of input to a single command, appending them all to its argument list. But specifying -I % makes xargs put the input at the specified place in the command, and only put one line there at a time, running echo as many times as required.



来源:https://stackoverflow.com/questions/23078897/how-to-add-text-at-the-end-of-each-line-in-unix

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