I’m trying to learn sed. Whilst trying to learn I entered the following lines in my terminal.
~/tmp>$ cat sedtest
a
sed will enjoy writing over this
I love cats, lovely
b
sed will really really enjoy writing over this
sed will really really hate writing over this
c
~/tmp>$ sed -n '/a/,/b/p' sedtest
a
sed will enjoy writing over this
I love cats, lovely
b
sed will really really enjoy writing over this
sed will really really hate writing over this
c
~/tmp>$
Why does my sed statement print all lines? I expect it to only print in between lines that contain the letters a and b inclusive.
>Solution :
I expect it to only print in between lines that contain the letters a and b inclusive.
That’s not what your command /a/,/b/p does. What it currently does is printing all ranges that start with a line containing a and end with a line containing b, because x,y means "range starting with line matching x and ending with line matching y". Note that if a range starts but never ends, then it spans the rest of the document:
1 / a
2 | sed will enjoy writing over this
3 | I love cats, lovely
4 \ b
5 / sed will really really enjoy writing over this
6 | sed will really really hate writing over this
7 | c
\______(end of document)
As you can see here, your specification is matching two ranges, both of which are getting printed. The first range starts at line 1 which contains a and ends at line 4 which contains b. The second range starts at line 5 which also contains a (in "really") and ends at the end of the document because there is no following line that contains b. These two ranges happen to cover all of your lines, so everything gets printed. (If you were to insert a line xyz before line 1 or between lines 4 and 5, that line would not get printed, as it would not be contained in any matching ranges.)
If you wanted to match only lines that contain both a and b (of which none exist in your example right now, by the way) then you’d have to use /a/{/b/p}. What this does is that for lines matching /a/, the next command is executed. That next command however is now a group of two things, /b/ and p, so it says "if line contains a then check if line contains b, and if that’s the case too, then print".