Monday, May 6, 2024
5
rated 0 times [  5] [ 0]  / answers: 1 / hits: 15594  / 2 Years ago, sun, october 9, 2022, 5:14:07

I've seen multiple answers to delete a single line with sed or grep, 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 line export NAME=variable (content shouldn't matter), and the following blank line. The export variable names are dynamic, but the comment will always be the same. There could be other export variables without the above comment which I do not want to delete.



How can I accomplish this?


More From » command-line

 Answers
1

With the newer version of GNU sed (comes with Ubuntu), you can match the newlines literally:



sed -z 's/#Set environment variable
export [^
]+

//g' file.txt



  • -z option will treat the lines of input files as terminated by ASCII NUL rather than newline, thus we can use
    to match the new lines


  • #Set environment variable
    will match the first line (with new line)


  • export [^
    ]+
    will match the second line starting with export


  • As the third line is blank simply
    will do


  • Then 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
export [^
]+

//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
export [^
]+

//g' file.txt
#Set environment variable
export NAME=value
#some text

check
value

export some=value

foo bar

[#19499] Monday, October 10, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
moloy

Total Points: 457
Total Questions: 93
Total Answers: 119

Location: Romania
Member since Wed, Dec 29, 2021
2 Years ago
;