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 with export
As the third line is blank simply \n
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\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
If you want to use read
to pass the names, and you want to delete lines that contain the names:
read deletename; sed "/$deletename/d" test.txt
then press enter and read
waits for you to enter something, so type whatever you want deletename
to be, for example 0
, then press enter again and the sed
command is executed. The contents of test.txt
will appear in the terminal, but all the lines that contain 0
, or whatever you typed, will be deleted from the stream (NOT from the file)
If you only want to delete the names themselves it's like this:
read deletename; sed "s/$deletename//g" test.txt
If you then type 0
, then every instance of 0
will be deleted.
You can redirect (or tee
) the output to a new file, or if you want to modify the file in place, use the -i
flag (after testing)
read deletename; sed -i "/$deletename/d" test.txt
In this case you will see no output; the changes will be written to the file instead of displayed in the terminal (on STDOUT).
You need to use double quotes to allow parameter expansion, as single quotes will suppress it. but the most correct way, I think, although not necessary in this simple case, it to use single quotes around the other parts of the expression and quote the variable normally:
sed 's/'"$deletename"'//g' test.txt
Best Answer
You just have to escape the backslash (escape the escape!)