從文件中刪除文字

從文件中刪除文字

我想從中刪除一些文字file1.txt

我將文字放入文件中tmp並執行以下操作:

grep -f tmp file.txt

但它只給了我差別。

問題是如何消除 的差異file.txt

答案1

這樣做grep -f tmp file.txt將顯示包含單字的所有行text(假設tmp只包含單字text)。如果您想顯示所有不包含單字文字的行,您需要使用選項-v來反轉匹配:

$ grep -v 'text' file.txt

如果列印文件中的所有行但僅刪除所有出現的textthen:

$ sed 's/text//g' 

答案2

如果您想從file.txt包含text種子行的行中刪除行,那麼您可以執行以下操作:

sed '/text/d' file.txt

或者

sed -n '/text/!p' file.txt

答案3

你想做的是

grep -Fvf tmp file.txt

man grep

   -f FILE, --file=FILE
          Obtain patterns from FILE, one per line.   The
          empty   file   contains   zero  patterns,  and
          therefore matches nothing.  (-f  is  specified
          by POSIX.)
   -F, --fixed-strings
          Interpret PATTERN as a list of fixed  strings,
          separated  by  newlines, any of which is to be
          matched.  (-F is specified by POSIX.)
   -v, --invert-match
          Invert  the  sense of matching, to select non-
          matching lines.  (-v is specified by POSIX.)

因此,-f告訴grep您讀取將從文件中搜尋的模式清單。-F是必需的,因此grep不會將這些模式解釋為正規表示式。因此,給定一個像 之類的字串foo.bar.將會被視為文字.而不是「匹配任何字元」。最後,-v反轉匹配,因此grep將僅列印那些與 中任何模式都不匹配的行tmp。例如:

$ cat pats 
aa
bb
cc
$ cat file.txt 
This line has aa
This one contains bb
This one contains none of the patterns
This one contains cc
$ grep -Fvf pats file.txt 
This one contains none of the patterns

答案4

我所做的是:

sed '/text_to_delete/d' filename | sponge filename

這將對原始檔案進行更改。

相關內容