Skip to content
Advertisement

sed pattern matching between lines

I am trying to write a sed script to only output the lines of a file if the line has the /pattern/ and is between line x and line y. I have the following:

./select.sed -n test.txt

select.sed:

#!/usr/bin/sed -f
/pattern/p

If my text.file is the the following:

1 line 1
2 pattern
3 line 3
4 pattern
5 line 5

The desired output would be

2 pattern

4 pattern

How would I set a range for lines 2-4 and only print values with “pattern”?

Advertisement

Answer

Try:

sed -n 'x,y{/regexp/p}' file
  • -n means do not print pattern space automatically.
  • x,y means operate only on lines between x. and y. line.
  • /regexp/p means print pattern space if regexp matches against pattern space.
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement