bash - 从bash中的句子中删除特定单词?

标签 bash shell sed

我想使用 bash 脚本从句子中删除否定词。
我的意思是消极的话:

[dull,boring,annoying,bad]
我的文件正文 text.txt包含这句话:
These dull boring cards are part of a chaotic board game ,and bad for people 
我正在使用这个脚本
array=( dull boring annoying bad  )
for i in "${array[@]}"
do
cat $p  | sed -e 's/\<$i\>//g' 
done < my_text.txt
但是我得到了以下错误的结果:
These boring cards are part of a chaotic board game ,and bad for people 
正确的输出必须是这样的:
These cards are part of a chaotic board game ,and for people 

最佳答案

首先,假设 $p 是存在的文件
然后使用这个脚本

while read p 
do 
  echo $p | sed  -e 's/\<dull\>//g' | sed -e 's/\<boring\>//g' | sed -e 's/\<annoying\>//g'|sed -e 's/\<bad\>//g' > my_text.txt
  
 cat my_text.txt
 
done < my_text.txt

此脚本的输出:
These  cards are part of a chaotic board game ,and  for people

或者可以使用这个脚本,你必须使用双引号,而不是单引号来扩展变量。
array=( dull boring annoying bad )
for i in "${array[@]}"
do
    sed -i -e "s/\<$i\>\s*//g" my_text.txt
done
sed -i开关替换在线。sed -e将脚本添加到要执行的命令中。
要了解有关 sed 命令的更多信息,您可以在终端中使用 man sed

关于bash - 从bash中的句子中删除特定单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65873817/

相关文章:

linux - ./executable 和 . 之间的区别可执行的

linux - 在 scp 的简单函数包装器中使用代字号 ~ 的问题

bash - 使用 AWS CLI 选择实例内的 Autoscaling 组标签

bash - 对于不引用可执行文件的命令,等同于 "which"的是什么?

bash - 使用 unix shell 脚本发送电子邮件

shell - 如何使用 sed 替换整行(两个单词之间)?

Linux 命令行帮助 |从文件中提取特定部分

unix - 使用 sed 更改/etc/fstab

bash - bashrc 中的 $MSYSTEM 变量

Java Runtime.getRuntime.exec() 返回 null 但在 shell 中返回有效字符串