组合两个相互依赖的命令的 sed 命令

sed command that combine two command that are dependant on each other

我需要 sed 命令的帮助,该命令将 birthday 行复制到标准输出,删除所有以“A”开头的行。 假设我的 sample.txt 文件如下所示:

A birthday is very much celebrated. 
Today is my birthday.
I can celebrate my birthday. 
A man can do anything.

这是示例输出:

Today is my birthday.
I can celebrate my birthday.

所以,对于生日线:

sed -n /birthday/p sample.txt

并删除以“A”开头的行:

sed -n '/^A/!p' sample.txt

现在,我很困惑如何将这两行结合起来,以便它们可以根据问题工作。

你要的是pipe operator|。通过将 STDOUT 连接到 STDIN,它将左侧命令的输出 'pipes' 输出到右侧命令。

所以在你的情况下你会这样做:

sed -n /birthday/p sample.txt | sed -n '/^A/!p'

编辑:格式化

使用 sed,不需要管道 - 您可以在打印包含“生日”的行之前删除以“A”开头的行:

sed -n '/^A/d; /birthday/p' file

或使用 sed 的默认打印操作(不通过 -n 选项禁用它):删除不包含“生日”的行。任何未被删除的行都将打印到标准输出。

sed '/^A/d; /birthday/!d' file

使用此方法,可以交换地址的顺序而不影响逻辑:/birthday/!d; /^A/d 产生相同的输出。

这可能适合您 (GNU sed):

sed '/^A/d;/birthday/!d' file

如果某行以 A 开头,则将其删除并删除所有其他没有生日的行。

或:

sed -n '/^[^A].*birthday/p' file

打印不以 A 开头且包含 birthday.

的行