Remove specific words from sentences in 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

中使用

您想要运行从数组生成的单个sed脚本。

printf 's/\<%s\>//g' "${array[@]}" |
sed -f - my_text.txt

如果您的sed不接受-f -从标准输入读取脚本,您需要重构一点。

同样,<>作为词边界可能不被你的sed;如果你有不同的方言,也许可以在两个地方尝试b

…或者在最坏的情况下,如果您的sed确实空闲,则切换到Perl。当然,也许可以把Bash全部重构出来,然后完全用Perl来完成。

perl -pe 'BEGIN { $re = "\b(" . join("|", qw(
dull boring annoying bad  )) . ")\b" }
s/$re//go' my_text.txt

最新更新