删除特定范围内的行之间包含图案的行

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

我想完全删除包含忽略前几行的模式的行。我试过:

$ sed -i '2,$s/pattern/d' file.txt

但它说

unterminated's' command

例如我有一个文件:

pattern # important one, not to be removed

some line1
some line2

pattern some content

another line3

pattern another content

another line4

所以,我想要

pattern # important one, not to be removed

some line1
some line2


another line3


another line4

如果我使用

sed -i '2,$s/pattern//' file.txt
那么它不会完全删除该行,有些字符不在模式中,即使它必须被删除。

bash sed
2个回答
0
投票

s
命令用于“搜索和替换”,而您缺少替换部分。

d
命令采用模式。两个指定 2 个模式,使用
{...}
块。

例如,从数字1到20中,删除包含3或8的数字,但仅限于数字5到15之间

seq 20 | sed '5,15{/[38]/d;}'
1
2
3
4
5
6
7
9      <<< "8" removed
10
11
12
14     <<< "13" removed
15
16
17
18
19
20

0
投票

sed
中执行此操作的最简单方法可能是跳过您想要确保不会受到影响的行,而不是选择您想要考虑的行,然后在这些行中子选择您真正想要删除的行。 示例:

sed '1b;/pattern/d` file.txt

说明:

这是两条独立的规则,用分号 (

;
) 分隔。

  • 第一个具有地址

    1
    (按行号选择第 1 行)和命令
    b
    (以这种形式结束当前的 sed 循环并开始新的循环)。
    sed
    的默认行为是在每个循环结束时、在读取下一行之前打印其模式空间,因此这只会传递第一行。

  • 第二个地址为

    /pattern/
    ,它选择那些尚未跳过但要删除的行。 当然,
    d
    命令会删除它们。

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