How do I use a new-line replacement in a BSD sed?

↘锁芯ラ 提交于 2019-11-26 09:45:10

问题


Greetings, how do I perform the following in BSD sed?

sed \'s/ /\\n/g\'

From the man-page it states that \\n will be treated literally within a replacement string, how do I avoid this behavior? Is there an alternate?

I\'m using Mac OS Snow Leopard, I may install fink to get GNU sed.


回答1:


In a shell, you can do:

    sed 's/ /\
/g'

hitting the enter key after the backslash to insert a newline.




回答2:


Another way:

sed -e 's/ /\'$'\n/g'

See here.




回答3:


For ease of use, i personally often use

cr="\n" 
# or (depending version and OS)
cr="
"

sed "s/ /\\${cr}/g"

so it stays on 1 line.




回答4:


To expand on @sikmir's answer: In Bash, which is the default shell on Mac OS X, all you need to do is place a $ character in front of the quoted string containing the escape sequence that you want to get interpreted. Bash will automatically translate it for you.

For example, I removed all MS-DOS carriage returns from all the source files in lib/ and include/ by writing:

grep -lr $'\r' lib include | xargs sed -i -e $'s/\r//'
find . -name '*-e' -delete

BSD grep would have interpreted '\r' correctly on its own, but using $'\r' doesn't hurt.

BSD sed would have misinterpreted 's/\r//' on its own, but by using $'s/\r//', I avoided that trap.

Notice that we can put $ in front of the entire string, and it will take care of all the escape sequences in the whole string.

$ echo $'hello\b\\world'
hell\world


来源:https://stackoverflow.com/questions/1421478/how-do-i-use-a-new-line-replacement-in-a-bsd-sed

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