Delete multiple lines from file when text is found
Solution 1
With the newer version of GNU sed
(comes with Ubuntu), you can match the newlines literally:
sed -z 's/#Set environment variable\nexport [^\n]\+\n\n//g' file.txt
-z
option will treat the lines of input files as terminated by ASCII NUL rather than newline, thus we can use\n
to match the new lines#Set environment variable\n
will match the first line (with new line)export [^\n]\+\n
will match the second line starting withexport
As the third line is blank simply
\n
will doThen we replace the whole pattern matched with blank to keep the desired portion
In you want to overwrite the file with the modified content:
sed -zi.bak 's/#Set environment variable\nexport [^\n]\+\n\n//g' file.txt
The original file will be retained as file.txt.bak
, if you don't want that just use sed -zi
.
Here is a test:
$ cat file.txt
#Set environment variable
export NAME=value
#some text
#Set environment variable
export NAME=value
check
value
export some=value
#Set environment variable
export NAME=value
foo bar
$ sed -z 's/#Set environment variable\nexport [^\n]\+\n\n//g' file.txt
#Set environment variable
export NAME=value
#some text
check
value
export some=value
foo bar
Solution 2
It is very easy to do this with standard sed's delete command:
cp ~/.profile ~/.profile.bak
sed '/#Set environment variable/,+2 d' <~/.profile.bak >~/.profile
Be careful with your ~/.profile
Related videos on Youtube
Chris G
Updated on September 18, 2022Comments
-
Chris G over 1 year
I've seen multiple answers to delete a single line with
sed
orgrep
, but I'm in need to search for a line, delete that one, and the 2 proceeding lines. For example, in the file~/.profile
I have lines like:#Set environment variable export NAME=value # (blank line here)
So I'd like to search for
#Set environment variable
, and delete it, then delete the next lineexport NAME=variable
(content shouldn't matter), and the following blank line. Theexport
variable names are dynamic, but the comment will always be the same. There could be otherexport
variables without the above comment which I do not want to delete.How can I accomplish this?
-
heemayl almost 9 yearsthis is not right....it will blindly remove the next two lines after match regardless of the contents....also you can just use
sed -i
instead of taking a backup beforehand.. -
ludvik02 almost 9 years@heemayl : but original post said "(content shouldn't matter)", at least for the "export" line. You might be right with the blank line, though.