如何用制表符替换换行符?
我有如下所示的模式,
hi
hello
hallo
greetings
salutations
no more hello for you
我尝试使用以下命令用制表符替换所有换行符,
sed -e "s_/\n_/\t_g"
但它不起作用。
有人可以帮忙吗?我正在 sed/awk 中寻找解决方案。
I have pattern like below
hi
hello
hallo
greetings
salutations
no more hello for you
I am trying to replace all newlines with tab using the following command
sed -e "s_/\n_/\t_g"
but it's not working.
Could anybody please help? I'm looking for a solution in sed/awk.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
我认为
tr
这里更好:正如 Nifle 在评论中建议的那样,
newlines
这里是保存原始文本的文件的名称。由于 sed 是面向行的,因此在这种情况下使用它会更加复杂。
tr
is better here, I think:As Nifle suggested in a comment,
newlines
here is the name of the file holding the original text.Because
sed
is so line-oriented, it's more complicated to use in a case like this.不确定你想要的输出
not sure about output you want
-s 连接每个单独输入文件的所有行
命令行命令。每行的换行符
除了每个输入文件中的最后一行被替换为
制表符,除非 -d 选项另有指定。
-s Concatenate all of the lines of each separate input file in
command line order. The newline character of every line
except the last line in each input file is replaced with the
tab character, unless otherwise specified by the -d option.
您无法使用
sed
逐行替换换行符。您必须累积行并替换它们之间的换行符。这个 sed 脚本会累积所有行并消除除最后
一行之外的所有换行符:顺便说一句,您的 sed 脚本 sed -e "s_/\n_/\ t_g" 试图说“将所有斜杠后跟换行符替换为斜杠后跟制表符”。下划线承担了
s
命令的分隔符作用,以便斜杠可以更轻松地用作搜索和替换的字符。You can't replace newlines on a line-by-line basis with
sed
. You have to accumulate lines and replace the newlines between them.This
sed
script accumulates all the lines and eliminates all the newlines but the last:By the way, your
sed
scriptsed -e "s_/\n_/\t_g"
is trying to say "replace all slashes followed by newlines with slashes followed by tabs". The underscores are taking on the role of delimiters for thes
command so that slashes can be more easily used as characters for searching and replacing.另外,如果使用变量、此处字符串或此处文档:
Also if using Variables, Here Strings or Here Documents:
与 HackerRank 上的文本处理挑战类似,这里是解决方案以及描述:
-s
:并排列出行。-d'\t'
:将分隔符设置为制表符。该命令的简短版本是:
请注意,使用
-s
选项时,tab
是默认分隔符。Similar to the Text Processing challenge on HackerRank, here is the solution along with the description:
-s
: lists the lines side by side.-d'\t'
: sets the delimiter to a tab.The short version of the command is:
Note that
tab
is the default delimiter when using the-s
option.您的 sed 脚本就快到了,您只需将其更改为:
\
就足以转义,您不需要添加_
并且您需要在末尾的
g
之前添加/
让 sed 知道这是脚本的最后一部分。You are almost there with your sed script, you'd just need to change it to:
The
\
is enough for escape, you don't need to add_
And you need to add the
/
beforeg
at the end to let sed know that this is the last part of the script.