如何使用awk替换换行符及其转义序列?

时间:2022-06-05 00:02:45

I'm asking for an awk solution because the sed solution sed ':a;N;$!ba;s/\n/ /g' does NOT get the last newline character usually present in files. My problem is that if I have a stream of data, every single newline character INCLUDING the one usually present at the end of outputs generated by programs like echo needs to be replaced with \n (raw). tr does not work because it cannot substitute in strings (which \\n is), only individual characters.

我要求一个awk解决方案,因为sed解决方案sed':a; N; $!ba; s / \ n / / g'不会获得通常存在于文件中的最后一个换行符。我的问题是,如果我有一个数据流,那么包含通常出现在echo等程序生成的输出末尾的每个换行符都需要用\ n(原始)替换。 tr不起作用,因为它不能替换字符串(\ n是\ n),只能替换单个字符。

As example, upon piping:

例如,在管道上:

echo -e "This is\na test."

to awk, I ought to get:

要awk,我应该得到:

This is\na test.\n

in return.

作为回报。

1 个解决方案

#1


2  

$ echo -e "This is\na test." | awk -v ORS='\\n' '1'
This is\na test.\n$

The $ at the end of the output is my prompt.

输出结尾的$是我的提示。

#1


2  

$ echo -e "This is\na test." | awk -v ORS='\\n' '1'
This is\na test.\n$

The $ at the end of the output is my prompt.

输出结尾的$是我的提示。