本文介绍了使用终端从文件中删除多个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个单词列表,它们要从文件 file.txt 中删除.我该如何使用终端.

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.

推荐答案

假设:

  • 替换仅应出现在整个单词上,而不仅仅是任何子字符串.
  • 替换应该在就地发生-即,结果应写回到输入文件中.
  • 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 (改编自@jaypal的评论):

  • 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
    

    这篇关于使用终端从文件中删除多个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    06-13 05:37