使用终端从文件中删除多个单词

时间:2014-06-09 19:14:39

标签: bash edit

我有一个单词word1 word2 word3列表,我想从文件file.txt中删除它。我怎么能用终端做到这一点。

2 个答案:

答案 0 :(得分:1)

 cat file.txt | sed "s/word1//g" | sed "s/word2//g" 

如果要将内容写入新文件,请执行以下操作:

 cat file.txt | sed "s/word1//g" | sed "s/word2//g" > newfile.txt

答案 1 :(得分:1)

假设:

  • 只应对整个字进行替换,而不仅仅是任何子字符串。
  • 替换应该就地 - 即结果应该写回输入文件。

  • GNU sed(改编自@ jaypal')

    sed -r -i 's/\b(word1|word2|word3)\b//g' file.txt
    
  • FreeBSD / OSX sed

    sed -E -i '' 's/[[:<:]](word1|word2|word3)[[:>:]]//g' file.txt
    

搜索词的变体解决方案可以是彼此的子串

# Array of sample search words.
words=( 'arrest' 'arrested' 'word3' )

# Sort them in reverse order and build up a list of alternatives
# for use with `sed` later ('word3|arrested|arrest').
# Note how the longer words among words that are substrings of
# each other come before the shorter ones.
reverseSortedAlternativesList=$(printf '%s\n' "${words[@]}" | sort -r  | tr '\n' '|')
# Remove the trailing '|'.
reverseSortedAlternativesList=${reverseSortedAlternativesList%|}

# GNU sed:
sed -r -i 's/\b('"$reverseSortedAlternativesList"')\b//g' file.txt

# FreeBSD/OSX sed:
sed -E -i '' 's/[[:<:]]('"$reverseSortedAlternativesList"')[[:>:]]//g' file.txt