使用 sed 替换多行 [英] Replace multiple lines using sed

查看:61
本文介绍了使用 sed 替换多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以为我理解 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.

test.txt:

hi
why
huh
hi
why
huh

test2.txt:

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 concatenate why to hi, leaving in the pattern space the string hi\nwhy. This string is not matched by the s/// command, so the line is just printed. Next time, you have the string huh in the pattern space and concatenate hi to it. Just in the next line you will have why\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 替换多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆