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

我想使用 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

  • There is more than one solution to the question, and the solution that you have raised is also good, thanks for the important remarks that you provided to me .
  • Running multiple static `sed` scripts in a chain or a loop betrays a fundamental lack of `sed` understanding. It's a scripting language, after all, albeit a primitive one.

以上是从bash中的句子中删除特定单词?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>