我的模式如下

hi
hello
hallo
greetings
salutations
no more hello for you

我正在尝试使用以下命令替换所有换行符

sed -e "s_/\n_/\t_g"

但它不起作用。

有人可以帮忙吗?我正在寻找sed / awk的解决方案。

有帮助吗?

解决方案

不确定您想要的输出

# awk -vRS="\n" -vORS="\t" '1' file
hi      hello   hallo   greetings       salutations     no more hello for you 

其他提示

这里 tr 更好,我想:

tr "\n" "\t" < newlines 

正如Nifle在评论中所建议的那样, newlines 这里是保存原始文本的文件的名称。

因为 sed 是如此面向行,所以在这种情况下使用它会更复杂。

sed '$!{:a;N;s/\n/\t/;ta}' file

您不能使用 sed 逐行替换换行符。您必须累积行并在之间替换换行符

text abc\n    <- can't replace this one

text abc\ntext def\n    <- you can replace the one after "abc" but not the one at the end

这个 sed 脚本累积了所有行并删除了所有换行但是最后一行:

sed -n '1{x;d};${H;x;s/\n/\t/g;p};{H}'

顺便说一下,你的 sed 脚本 sed -e&quot; s _ / \ n _ / \ t_g&quot; 试图说“替换所有斜杠后跟换行符斜杠后跟选项卡“。下划线正在扮演 s 命令的分隔符角色,这样斜杠就可以更容易地用作搜索和替换的字符。

paste -s

-s连接每个单独输入文件的所有行                  命令行顺序。每一行的换行符                  除了每个输入文件中的最后一行被替换为                  制表符,除非-d选项另有指定。

您的sed脚本几乎就在那里,您只需要将其更改为:

sed -e "s/\n/\t/g"

\ 足以逃脱,你不需要添加 _ 你需要在最后的 g 之前添加 / ,让sed知道这是脚本的最后一部分。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top