ファイルからテキストを削除する

ファイルからテキストを削除する

からテキストの一部を削除したいですfile1.txt

ファイルにテキストを入れてtmp、次の操作を実行します。

grep -f tmp file.txt

しかし、それは私に違いだけを与えます。

問題は、 との差異をどのように取り除くかということですfile.txt

答え1

を実行するとgrep -f tmp file.txt、単語 を含むすべての行が表示されますtext(tmp単語 のみが含まれていると仮定しますtext)。単語 text を含まないすべての行を表示する場合は、-v一致を反転するオプションを使用する必要があります。

$ grep -v 'text' file.txt

ファイル内のすべての行を印刷し、 のすべての出現を削除する場合は、text次のようになります。

$ 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-Fgrepfoo.bar..-vgreptmp

$ 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

これにより、ソース ファイルに変更が加えられます。

関連情報