如何正确使用sed变量?

  • 本文关键字:变量 sed 何正确 sed
  • 更新时间 :
  • 英文 :


我需要在sed命令中使用字符串变量。我的尝试是在script.sh中给出的,它没有做我想要的,我假设是因为我的变量包含需要sed计算的字符。我在linux中工作bash.

input.txt

delicious.banana
gross.apple

script.sh

adjectives="delicious|gross|bearable|yummy"
sed "s/($adjectives).//g" input.txt > output.txt

output.txt所需的

banana
apple
当前

output.txt

deliciousbanana
grossdapple

非gnu sed在BRE(基本正则表达式模式)中不能与|一起工作。我建议使用ERE(扩展正则表达式模式)使用-E,作为奖励,您可以消除所有转义:

adjectives="delicious|gross|bearable|yummy"
sed -E "s/($adjectives).//g" input.txt
banana
apple

最新更新