3

I have a file with the following contents:

Windows user
I love windows
Windows 10
# I like it
# I want to keep these two lines
Just started with my job
New to shell scripting as well
New to Mac
Please help!

#EOF

I want to delete all the lines:

starting from "I love windows" to "New to shell scripting as well", but keep the comments that are present between these lines.

So, the desired output should appear as below:

Windows user
# I like it
# I want to keep these two lines
New to Mac
Please help!

#EOF

I used sed command to delete the range of lines using the line numbers

sed '2,7d' file

But this command deletes the comments as well, which I want preserved.

0

1 Answer 1

5

Try using:

sed '2,7{/^[[:blank:]]*#/!d}' infile

This is normally deleting lines from 2~7 but not the lines that starts with a hash as known as a commented line.

The [[:blank:]] character class is used to match and keep those lines that it's a commented line but took whitespaces at behind too either zero or more whitespace.

To be more specifically using the patterns given:

sed '/I love windows/,/New to shell scripting as well/ {/^[[:blank:]]*#/!d}' infile

standard-Complaint sed solution would be:

sed -e '2,7{' -e '/^[[:space:]]*#/!d' -e '}' infile

to read the line number from a variable, just double-quote your variables like "$line" (related: How do I use variables in a sed command?.)

line=2; sed -e "$line"',7{' -e '/^[[:space:]]*#/!d' -e '}' infile

The output is:

Windows user
# I like it
# I want to keep these two lines
New to Mac
Please help!

#EOF
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .