【问题标题】:how to use result from a pipe in the next sed command?如何在下一个 sed 命令中使用管道的结果?
【发布时间】:2026-01-17 14:40:01
【问题描述】:

我想使用 sed 来执行此操作。我有 2 个文件:

keys.txt:
host1
host2

test.txt
host1 abc
host2 cdf
host3 abaasdf

我想使用 sed 删除 test.txt 中包含 keys.txt 中的关键字的所有行。所以 test.txt 的结果应该是

host3 abaasdf

谁能告诉我如何用 sed 做到这一点?

谢谢,

【问题讨论】:

标签: sed


【解决方案1】:

我建议为此使用grep(尤其是fgrep,因为不涉及正则表达式),所以

fgrep -v -f keys.txt test.txt 

做得很好。使用sed 很快就可以了:

sed -i.ORIGKEYS.txt ^-e 's_^_/_' -e 's_$_/d_' keys.txt
sed -f keys.txt test.txt

(这会将原始 keys.txt 原位修改 - 带有备份 - 为可源化的 sed 脚本。)

【讨论】:

  • 如果我做 cat keys.txt | sed ...(删除此键)。我该怎么做?
  • 你做不到。 sed 有能力,但没有那么有能力 AFAIK。
  • 至少对于 GNU sed,它通过在脚本中的管道来工作,例如:sed 's_^_/_; s_$_/d_' keys.txt | sed -f - test.txt
  • TIL 关于那个选项@Thor,谢谢(但它仍然不是猫)
【解决方案2】:

fgrep -v -f 是最好的解决方案。这里有几个选择:

commjoin 的组合

comm -13 <(join keys.txt test.txt) test.txt

或 awk

awk 'NR==FNR {key[$1]; next} $1 in key {next} 1' keys.txt test.txt

【讨论】:

    【解决方案3】:

    这可能对你有用(GNU sed):

    sed 's|.*|/^&\\>/d|' keys.txt | sed -f - test.txt
    

    【讨论】:

      最近更新 更多