如何在 BSD sed 中使用换行符替换?
您好,我如何在 BSD sed 中执行以下操作?
sed 's/ /\n/g'
从手册页来看,它指出 \n 将在替换字符串中按字面意思处理,如何避免这种行为?有替代方案吗?
我使用的是 Mac OS Snow Leopard,我可以安装 fink 来获取 GNU sed。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在 shell 中,您可以执行以下操作:
在反斜杠后面按 Enter 键以插入换行符。
In a shell, you can do:
hitting the enter key after the backslash to insert a newline.
另一种方式:
请参阅此处。
Another way:
See here.
为了方便使用,我个人经常使用,
所以它保持在1行。
For ease of use, i personally often use
so it stays on 1 line.
扩展@sikmir的答案:在Bash(Mac OS X上的默认shell)中,您需要做的就是在包含您想要的转义序列的引用字符串前面放置一个
$
字符得到解释。 Bash 会自动为你翻译。例如,我通过编写以下内容从
\r' lib include | xargs sed -i -elib/
和include/
中的所有源文件中删除了所有 MS-DOS 回车符:BSD
grep
将会有单独正确解释'\r'
,但使用$'\r'
不会有什么坏处。BSD
sed
本身会误解's/\r//'
,但使用$'s/\r//'
,我避开了那个陷阱。请注意,我们可以将
s/\r//' find . -name '*-e' -delete$
放在整个字符串的前面,它将处理整个字符串中的所有转义序列。BSD
grep
将会有单独正确解释'\r'
,但使用$'\r'
不会有什么坏处。BSD
sed
本身会误解's/\r//'
,但使用$'s/\r//'
,我避开了那个陷阱。请注意,我们可以将
$
放在整个字符串的前面,它将处理整个字符串中的所有转义序列。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
\r' lib include | xargs sed -i -elib/
andinclude/
by writing: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
s/\r//' find . -name '*-e' -delete$
in front of the entire string, and it will take care of all the escape sequences in the whole string.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.