Question

I'm trying to pipe line numbers from grep to sed.

First I was extracting the start and end line of what I want to print with sed:

grep -n "Start" file1 | cut -d: -f 1 | head -n 1
grep -n "End" file1 | cut -d: -f 1 | head -n 1

Now I need to use these numbers to print everything from Start to End by line. E.g.

sed -ne '1,30w output1' file1

I'm not sure how this can be done as piping the line numbers to sed will be seen as "input" right?

Example:

Start
some text
some more text
End
Start
some text
some more text
End

As there's more than one start and end i cut of the rest of the line numbers from grep. And I'm supposed to combine grep and sed or is this not possible?

Was it helpful?

Solution 3

This might work for you (GNU sed):

sed -ne '/Start/,/End/w outputfile' -e '/End/q' file

This will write to outputfile the lines between the first Start and End and then quit and obviate the need to use grep too.

If you must use grep then perhaps:

sed -n "$(grep -n "Start" file | cut -d: -f 1 | head -n 1),$(grep -n "End" file | cut -d: -f 1 | head -n 1)"'p' file

OTHER TIPS

You can do it without grep

sed -n '/Start/,/End/w output1' file1

should work.

It looks like you want to print from the first occurrence of Start to the first subsequent occurrence of End, inclusive. That'd just be:

awk '/Start/{found=1} found{print; if (/End/) exit}' file
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top