bash sed 帮助:匹配和替换文字“\n”(不是换行符)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19762365/
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-18 08:29:21  来源:igfitidea点击:

sed help: matching and replacing a literal "\n" (not the newline)

linuxbashsedpattern-matchingnewline

提问by sam h

i have a file which contains several instances of \n.

我有一个包含多个\n实例的文件。

i would like to replace them with actual newlines, but sed doesn't recognize the \n.

我想用实际的换行符替换它们,但 sed 无法识别\n

i tried

我试过

sed -r -e 's/\n/\n/'
sed -r -e 's/\n/\n/'
sed -r -e 's/[\n]/\n/'

and many other ways of escaping it.

以及许多其他逃避它的方法。

is sed able to recognize a literal \n? if so, how?

sed 能够识别文字\n吗?如果是这样,如何?

is there another program that can read the file interpreting the \n's as real newlines?

是否有另一个程序可以读取将\n解释为真正的换行符的文件?

回答by Ashish

Can you please try this

你能试试这个吗

sed -i 's/\n/\n/g' input_filename

回答by Bryan Newman

$ echo "\n" | sed -e 's/[\][n]/hello/'

回答by Jotne

awkseems to handle this fine:

awk似乎处理这个罚款:

echo "test \n more data" | awk '{sub(/\n/,"**")}1'
test ** more data

Here you need to escape the \using \\

在这里你需要逃避\使用\\

回答by NeronLeVelu

1) sed work 1 line a t a time son no \n on 1 line only (it's removed by sed at read time into buffer). You should use N,n or H, h to fill the buffer with more than 1 line, and than \n appear inside. Be carreful, ^ and $ are no more end of line but end of string/buffer so \n are inside. 2) \n is recognize in search pattern, not in replace pattern. 2 ways for using it (sample)

1) sed 工作 1 行 ata time 儿子没有 \n 仅在 1 行(它在读取时被 sed 删除到缓冲区中)。您应该使用 N,n 或 H, h 用多于 1 行填充缓冲区,并且比 \n 出现在里面。小心, ^ 和 $ 不再是行尾而是字符串/缓冲区的结尾,所以 \n 在里面。2) \n 在搜索模式中识别,而不是在替换模式中。2种使用方法(示例)

sed s/\(\n\)bla/blabla/
sed s/\nbla/\
blabla\
/

first use a \n already inside as back reference (smaller line in replace pattern) second use a real new line

首先使用已经在里面的 \n 作为反向引用(替换模式中的较小行),然后使用真正的新行

so basicaly

所以基本上

sed "N
$ s/\(\n\)//g
"

work (but is a bit useless). I imagine that s/\(\n\)\n/\1/gis more what you want

工作(但有点无用)。我想那s/\(\n\)\n/\1/g是你更想要的