bash 在 sed 替换字符串中转义换行符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8991275/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 21:33:47  来源:igfitidea点击:

escaping newlines in sed replacement string

bashunixsedescapingsolaris

提问by spraff

Here are my attempts to replace a bcharacter with a newline using sedwhile running bash

这是我在运行时b使用换行符替换字符的尝试sedbash

$> echo 'abc' | sed 's/b/\n/'
anc

no, that's not it

不,不是这样

$> echo 'abc' | sed 's/b/\n/'
a\nc

no, that's not it either. The output I want is

不,也不是这样。我想要的输出是

a
c

HELP!

帮助!

采纳答案by jaypal singh

Looks like you are on BSD or Solaris. Try this:

看起来您使用的是 BSD 或 Solaris。尝试这个:

[jaypal:~/Temp] echo 'abc' | sed 's/b/\ 
> /'
a
c

Add a black slash and hit enter and complete your sedstatement.

添加黑色斜线并按 Enter 键并完成您的sed陈述。

回答by tboyce12

$ echo 'abc' | sed 's/b/\'$'\n''/'
a
c

In Bash, $'\n'expands to a single quoted newline character (see "QUOTING" section of man bash). The three strings are concatenated before being passed into sed as an argument. Sed requires that the newline character be escaped, hence the first backslash in the code I pasted.

在 Bash 中,$'\n'扩展为单引号换行符(请参阅 的“QUOTING”部分man bash)。这三个字符串在作为参数传递到 sed 之前被连接起来。Sed 要求对换行符进行转义,因此是我粘贴的代码中的第一个反斜杠。

回答by glenn Hymanman

You didn't say you want to globally replace all b. If yes, you want trinstead:

您没有说要全局替换所有b. 如果是,你想要tr

$ echo abcbd | tr b $'\n'
a
c
d

Works for me on Solaris 5.8 and bash 2.03

在 Solaris 5.8 和 bash 2.03 上对我有用

回答by CommaToast

In a multiline file I had to pipe through tr on both sides of sed, like so:

在多行文件中,我必须在 sed 的两侧通过 tr 进行管道传输,如下所示:

echo "$FILE_CONTENTS" | \ tr '\n' ¥ | tr ' ' ∑ | mySedFunction $1 | tr ¥ '\n' | tr ∑ ' '

echo "$FILE_CONTENTS" | \ tr '\n' ¥ | tr ' ' ∑ | mySedFunction $1 | tr ¥ '\n' | tr ∑ ' '

See unix likes to strip out newlines and extra leading spaces and all sorts of things, because I guess that seemed like the thing to do at the time when it was made back in the 1900s. Anyway, this method I show above solves the problem 100%. Wish I would have seen someone post this somewhere because it would have saved me about three hours of my life.

看到 unix 喜欢去掉换行符和额外的前导空格以及各种各样的东西,因为我猜这在 1900 年代制作时似乎是要做的事情。无论如何,我上面展示的这个方法 100% 解决了这个问题。希望我能看到有人在某处发布此信息,因为它可以为我节省大约三个小时的生命。

回答by Ravi Bhatt

echo 'abc' | sed 's/b/\'\n'/' 

you are missing ''around \n

你失踪''\n