问题描述
我以为我理解 sed 但我猜不是.我有以下两个文件,我想在其中用一个不同的行替换why"和huh"行.根本没有空格.
test.txt:
嗨为什么呵呵你好为什么呵呵
test2.txt:
1你好为什么呵呵你好为什么呵呵
以下两个命令给出以下结果:
sed "N; s/\n/yo/g" test.txt >输出.txt输出.txt:你好为什么呵呵你好哟sed "N; s/<why\/>\n<huh\/>/yo/g" test2.txt >输出2.txt输出2.txt:1你好哟你好为什么呵呵
我对 sed 有什么不了解?为什么不两个输出文件都包含以下内容:
嗨哟你好哟
你的表达几乎正确,但有两个问题:
如果你想把
why
作为一个词来匹配,你应该把\<
和\>
放在它周围.你确实在它周围放置了<
和\/>
.所以,第一个更正是:$ sed 'N;s/\<为什么\>\n\<huh\>/yo/g' test.txt
但它也行不通:
$ sed 'N;s/\\n\/yo/g' test.txt你好为什么呵呵你好哟
为什么只替换第二对线?好吧,在第一行,
N
命令将把why
连接到hi
,留在 模式空间字符串hi\nwhy
.此字符串与s///
命令不匹配,因此仅打印该行.下一次,您在模式空间中有字符串huh
并将hi
连接到它.就在下一行,您将在要替换的模式空间中有why\nhuh
.解决方案是仅在当前行是
why
时连接下一行,使用 地址/^why$/
:$ sed '/^why$/{N;s/\<为什么\>\n\<huh\>/yo/g}' test.txt你好哟你好哟
I thought I understood sed but I guess not. I have the following two files, in which I want to replace the "why" and "huh" lines with one different line. No whitespace at all.
hi
why
huh
hi
why
huh
1
hi
why
huh
hi
why
huh
The following two commands give the following results:
sed "N; s/<why\/>\n<huh\/>/yo/g" test.txt > out.txt
out.txt:
hi
why
huh
hi
yo
sed "N; s/<why\/>\n<huh\/>/yo/g" test2.txt > out2.txt
out2.txt:
1
hi
yo
hi
why
huh
What am I not understanding about sed? Why don't both output files contain the following:
hi
yo
hi
yo
Your expression is almost correct, but it has two problems:
If you want to match
why
as a word, you should put\<
and\>
around it. You did put just<
and\/>
around it. So, the first correction is:$ sed 'N; s/\<why\>\n\<huh\>/yo/g' test.txt
But it will not work, either:
$ sed 'N; s/\<why\>\n\<huh\>/yo/g' test.txt hi why huh hi yo
Why does it replace only the second pair of lines? Well, in the first line, the
N
command will concatenatewhy
tohi
, leaving in the pattern space the stringhi\nwhy
. This string is not matched by thes///
command, so the line is just printed. Next time, you have the stringhuh
in the pattern space and concatenatehi
to it. Just in the next line you will havewhy\nhuh
in the pattern space to be replaced.The solution is to concatenate the next line only when your current line is
why
, using the address/^why$/
:$ sed '/^why$/ {N; s/\<why\>\n\<huh\>/yo/g}' test.txt hi yo hi yo
这篇关于使用 sed 替换多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!