bash 在 awk 中用换行符替换 \n
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24574489/
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
replace \n with newline in awk
提问by Cotten
I'm tailing logs and they output \n
instead of newlines.
我正在拖尾日志,它们输出\n
而不是换行符。
I thought I'd pipe the tail
to awk
and do a simple replace, however I cannot seem to escape the newline in the regex. Here I'm demonstrating my problem with cat
instead of tail
:
我想我应该管tail
到awk
,做一个简单的替换,但我似乎无法逃脱正则表达式的换行符。在这里,我用cat
而不是展示我的问题tail
:
// test.txt
John\nDoe
Sara\nConnor
cat test.txt | awk -F'\n' '{ print "\n" }'
Desired output:
期望的输出:
John
Doe
Sara
Connor
Actual output:
实际输出:
John\nDoe
<- there is a newline here
Sara\nConnor
<- there is a newline here
So it looks like \\n
does not match the \n
between the first and last names in test.txt but instead the newline at the end of each line.
所以它看起来不像test.txt 中的名字和姓氏之间的\\n
匹配,\n
而是每行末尾的换行符。
It looks like \\n
is not the right way of escaping in the terminal right? This way of escaping works fine in e.g. Sublime Text:
看起来\\n
不是在终端中逃逸的正确方式吧?这种转义方式在 Sublime Text 中效果很好:
回答by Avinash Raj
How about this?
这个怎么样?
$ cat file
John\nDoe
Sara\nConnor
$ awk '{gsub(/\n/,"\n")}1' file
John
Doe
Sara
Connor
回答by DarkDust
Using GNU's sed
, the solution is pretty simple as @hek2mgl already answered (and that IMHO is the way it should work everywhere, but unfortunately doesn't).
使用 GNU 的sed
,解决方案非常简单,因为@hek2mgl 已经回答了(恕我直言,它应该在任何地方工作,但不幸的是没有)。
But it's bit tricky when doing it on Mac OS Xand other *BSD UNIXes.
但是在Mac OS X和其他 *BSD UNIXes上做这件事有点棘手。
The best way looks like this:
最好的方法是这样的:
sed 's/\n/\'$'\n''/g' <<< 'ABC\n123'
Then of course there's still AWK, @AvinashRaj has the correct answer if you'd like to use that.
然后当然还有 AWK,如果您想使用 @AvinashRaj 有正确的答案。
回答by Ed Morton
This will work with any sed on any system as it is THE portable way to use newlines in sed:
这将适用于任何系统上的任何 sed,因为它是在 sed 中使用换行符的可移植方式:
$ sed 's/\n/\
/' file
John
Doe
Sara
Connor
If it is possible for you input to contain a line like foo\\nbar
and the \\
is intended to be an escaped backslash then you cannot use a simple substitution approach like you've asked for.
如果您的输入可能包含一行,foo\\nbar
并且\\
旨在成为转义的反斜杠,那么您不能像您要求的那样使用简单的替换方法。
回答by user239558
Why use either awk
or sed
for this? Use perl
!
为什么要使用两种awk
或sed
此?使用perl
!
perl -pe 's/\n/\n/g' file
By using perl
you avoid having to think about posix compliance, and it will typically give better performance, and it will be consistent across all (most) platforms.
通过使用,perl
您不必考虑 posix 合规性,它通常会提供更好的性能,并且在所有(大多数)平台上都是一致的。
回答by hek2mgl
I would use sed
:
我会用sed
:
sed 's/\n/\n/g' file