Remove Text from File

Remove Text from File

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

4 Answers

Doing grep -f tmp file.txt will display all lines containing the work text (assume tmp just contins the work text). If 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' 
2

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

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

What I do is:

sed '/text_to_delete/d' filename | sponge filename

This will make the change to the source file.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

James H. Sterling
Author

James H. Sterling

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.