Remove specific words from sentences in bash?

笑着哭i 提交于 2021-02-20 19:14:12

问题


I want to remove negative words form sentence using bash script .

The negative words that i meant it :

[dull,boring,annoying,bad]

My file text text.txt contains this sentence :

These dull boring cards are part of a chaotic board game ,and bad for people 

I'm using this script

array=( dull boring annoying bad  )
for i in "${array[@]}"
do
cat $p  | sed -e 's/\<$i\>//g' 
done < my_text.txt

But I got the following wrong result:

These boring cards are part of a chaotic board game ,and bad for people 

The correct output must be like this :

These cards are part of a chaotic board game ,and for people 

回答1:


First, assuming $p is existed file Then used this Script

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

The output of this script :

These  cards are part of a chaotic board game ,and  for people

Or can use this script, You have to use double quotes, not single quotes to get variables expanded.

array=( dull boring annoying bad )
for i in "${array[@]}"
do
    sed -i -e "s/\<$i\>\s*//g" my_text.txt
done

The sed -i switch replace in line.
The sed -e to add the script to the commands to be executed.

To learn more about sed command you can used in your terminal man sed




回答2:


You want to run a single sed script, generated from the array.

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

If your sed does not accept -f - to read the script from standard input, you need to refactor a bit.

Similarly, \< and \> as word boundaries may not be supported by your sed; perhaps try \b in both places if you have a different dialect.

...or in the worst case switch to Perl if your sed is really spare. Though of course, maybe refactor out Bash altogether then, and do this entirely in Perl.

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


来源:https://stackoverflow.com/questions/65873817/remove-specific-words-from-sentences-in-bash

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!