3

I want to remove some text from file1.txt.

I put the text in the file tmp and do:

grep -f tmp file.txt

But it gives me only the difference.

The question is how to remove the difference from file.txt.

2
  • you can make a sed command script with the patterns in tmp .
    – Endoro
    Jun 10, 2013 at 11:53
  • Either remove "using sed or grep" from your question or remove "awk" from your tags.
    – Ed Morton
    Jun 10, 2013 at 12:33

4 Answers 4

10

Doing grep -f tmp file.txt will display all lines containing the word text (assume tmp just contains the word text). If you want to display all the lines that don't contain the word text you need to use the -v option to invert the match:

$ grep -v 'text' file.txt

If you print all the lines in the file but just remove all occurrences of text then:

$ sed 's/text//g' 
3
  • the tmp file contain the text that I want to remove from file.txt. ("text" is not a word). 'grep -v -f tmp file.txt > file_result.txt' file_result.txt : do not contain text which exist in tmp file Jun 10, 2013 at 11:31
  • grep works with lines not individual words.
    – iiSeymour
    Jun 10, 2013 at 11:33
  • You saved my day! :D
    – KayD
    Oct 26, 2022 at 16:23
5

If you want to remove lines from your file.txt which contains the line where text is seed then you can do something like:

sed '/text/d' file.txt

or

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

What you want to do is

grep -Fvf tmp file.txt

From 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.)

So, -f tells grep to read the list of patterns it will search for from a file. -F is needed so grep does not interpret these patterns as regular expressions. So, given a string like foo.bar, the . will be taken as a literal . and not as "match any character". Finally, the -v inverts the match so grep will print only those lines that do not match any of the patterns in tmp. For example:

$ 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
0

What I do is:

sed '/text_to_delete/d' filename | sponge filename

This will make the change to the source file.

1
  • 2
    No need to use sponge, just use '-i': sed -i '/text_to_delete/d' filename
    – Woftor
    Jan 23, 2017 at 15:58

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .