Replace literal “\r\n” in text file

亡梦爱人 提交于 2020-05-24 06:42:50

问题


I am trying to replace each \r\n in a text file with <p/>.

I have tried the following with no luck:

sed 's#\r\n#<p/>#g' test.txt
sed 's#\r\n#<p/>#g' test.txt
sed 's#/\r/\n#<p/>#g' test.txt
sed ':a;N;$!ba;s/\r\n/<p/>/g' test.txt

Here is the text in text.txt

https://www.pivotaltracker.com/story/\r\nhttps://www.pivotaltracker.com/story\r\n\r\nSome business text.\r\n\r\nSome business text. Task 123 is still a work in progress but we wanted it in develop to keep everything updated.

回答1:


All of the other answers have assumed that you are trying to handle Windows-style line endings and change them to paragraph tags.

To change the literal sequence of characters \r\n to something else, just use a global substitution:

sed 's!\\r\\n!<p/>!g' file

The \ themselves need to be escaped.




回答2:


cat file | tr -d '\r' | sed 's|$|</p>|g' | tr -d '\n'



回答3:


Line endings are much easier to manipulate with perl one-liners than with sed. This is totally untested, but should work (the only question in my mind is whether perl might do universal newline handling these days, in which case you'd never see a \r):

perl -e 'undef $/; while (<>) { s:\r\n:<p/>:g; print; }' test.txt > xtest.txt

or equivalently

perl -pe 'BEGIN { undef $/ } s:\r\n:<p/>:g' test.txt > xtest.txt

The key is undef $/ at the beginning, which makes perl read the entire of test.txt as one big long string; the obvious regex then Just Works.



来源:https://stackoverflow.com/questions/40380437/replace-literal-r-n-in-text-file

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