Deleting multiple words from a file using terminal

泪湿孤枕 提交于 2021-02-17 02:00:34

问题


I have a list of words word1 word2 word3 which I want to delete from a file file.txt. How can i do that using terminal.


回答1:


Assuming that:

  • Replacements should only occur for whole words, not just any substrings.
  • Replacements should occur in-place - i.e., the results should be written back to the input file.

  • GNU sed (adapted from @jaypal's comment):

    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
    

Variant solution in case the search words can be substrings of each other:

# 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



回答2:


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

If you want to write the content into a new file do this:

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


来源:https://stackoverflow.com/questions/24127301/deleting-multiple-words-from-a-file-using-terminal

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