remove text from file
Solution 1
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'
Solution 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
Solution 3
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
Related videos on Youtube
Ellouze Anis
Updated on September 18, 2022Comments
-
Ellouze Anis over 1 year
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
.-
Endoro almost 11 yearsyou can make a
sed
command script with the patterns intmp
. -
Admin almost 11 yearsEither remove "using sed or grep" from your question or remove "awk" from your tags.
-
-
Ellouze Anis almost 11 yearsthe 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
-
iiSeymour almost 11 yearsgrep works with lines not individual words.
-
Woftor over 7 yearsNo need to use sponge, just use '-i':
sed -i '/text_to_delete/d' filename