簡體   English   中英

從 bash 的句子中刪除特定單詞?

[英]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 

正確的 output 必須是這樣的:

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

這個腳本的output:

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

...或者在最壞的情況下切換到 Perl 如果您的sed真的很閑。 當然,也許那時完全重構出 Bash,並完全在 Perl 中完成。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM