我有一个单词word1 word2 word3
列表,我想从文件file.txt
中删除它。我怎么能用终端做到这一点。
答案 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