如何用制表符替换换行符?

问题描述 投票:0回答:7

我有如下的图案

hi
hello
hallo
greetings
salutations
no more hello for you

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

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

但它不起作用。

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

shell unix sed awk
7个回答
51
投票

tr
这里更好,我认为:

tr "\n" "\t" < newlines 

正如 Nifle 在评论中建议的那样,

newlines
这里是保存原始文本的文件的名称。

因为

sed
是面向行的,所以在这种情况下使用起来比较复杂。


13
投票

不确定你想要的输出

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

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

6
投票

您无法使用

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 "s_/\n_/\t_g"
 试图说“将所有斜杠后跟换行符替换为斜杠后跟制表符”。下划线承担 
s
 命令的分隔符作用,以便斜杠可以更轻松地用作搜索和替换的字符。


6
投票
paste -s

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


0
投票
还有:

tr "\n" "\t" <<< "a b c d "

```bash
paste -s <<< "a
b
c
d
"
    

-2
投票
您的 sed 脚本就快完成了,您只需将其更改为:

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

逃生的

\

就够了,不需要加
_
并且您需要在末尾的 
/
 之前添加 
g
,让 sed 知道这是脚本的最后一部分。

© www.soinside.com 2019 - 2024. All rights reserved.