Thursday, April 28, 2022

[SOLVED] Use variables in sed along with !d

Issue

MacOS. I have the following file from which I have to delete all lines between first and last including first. last appears multiple times in the file and I don't want to delete it.

$ cat sample.tf
some lines 1
some random 2
first
vdsvdfsv
vdsvdfsv
dfvbfbvfvfrver
bvevreverv
last
vfver
vever
end
last
some last
end
$

I am able to do it with following command

$ sed '/^first/,/^last/{/^last/!d;}' sample.tf
some lines 1
some random 2
last
vfver
vever
end
last
some last
end
$

But the challenge I have is my first and last are variables. To use variables, I have to use " and tried following command but it is trying to convert !d into the command from history. How can I achieve what I am trying to do.

$ echo $startstring
first
$ echo $endstring
last
$
$ sed "/^$startstring/,/^$endstring/{/^$endstring/!d;}" sample.tf
sed "/^$startstring/,/^$endstring/{/^$endstring/diff main.tf main.tf.good ;}" sample.tf
sed: 1: "/^first/,/^last/{/^last ...": extra characters at the end of d command
$

$ !d
diff main.tf main.tf.good
$

Solution

Suggestion from @William Pursell to mix-and-match quotes worked for me.

sed "/^$startstring/,/^$endstring/{/^$endstring/"'!d;}' sample.tf


Answered By - bijujo
Answer Checked By - Katrina (WPSolving Volunteer)