tr command not able to direct the Output?

馋奶兔 提交于 2019-12-10 14:18:36

问题


I have got a file file.txt witch has got these entries

NY

LA

SF

I ran the command tr '\n' ',' < file.txt and it successfully deleted all of the newline characters.

I need all of this output in the same file.txt file, so I redirected the output like this

tr '\n' ',' < file.txt > file.txt,

but It does not put anything in the file.txt and the resultant file is empty, Can anyone explain to me why the output of tr is getting lost due to redirection.


回答1:


because it opens the output file first which deletes what is in the file and then feels nothing into the tr command and back out into the empty file

tr '\n' ',' < file.txt > file2.txt 

will work




回答2:


since you have tagged your question with sed, I suggest a sed oneliner, also sed could change your file "in-place" with option "-i"

sed -i ':a $!N; s/\n/,/; ta' file

or with awk

 

awk '{x=x""sprintf($0",")}END{gsub(/,$/,"",x);print x}' file

no like sed, awk has no "in-place" changing option, you have to :

awk '...' file > /tmp/mytmp && mv /tmp/mytmp file



回答3:


If you just want to replace the newline with , you can us this

awk 'ORS=","' temp.txt > file.txt



来源:https://stackoverflow.com/questions/14675849/tr-command-not-able-to-direct-the-output

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