Pregunta

I have a file t.txt of the form:

abc 0
file content1
file content2
abc 1
file content3
file content4
abc 2
file content5
file content6

Now I want to retain all the content between abc 1 and abc 2 i.e. I want to retain:

file content3
file content4

For this I am using sed:

sed -e "/abc\s4/, /abc\s5/ p" t.txt > j.txt

But when I do so I get j.txt to be a copy of t.txt. I dont know where I am making the mistake..can someone please help

¿Fue útil?

Solución

You can use this sed:

$ sed -n '/abc 1/,/abc 2/{/abc 1/d; /abc 2/d; p}' file
file content3
file content4

Explanation

  • /abc 1/,/abc 2/ selectr range of lines from the one containing abc 1 to the one containing abc 2. It could also be /^abc 1$/ to match the full string.
  • p prints the lines. So for example sed -n '/file/p' file will print all the lines containing the string file.
  • d deletes the lines.

'/abc 1/,/abc 2/p' alone would print the abc 1 and abc 2 lines:

$ sed -n '/abc 1/,/abc 2/p' file
abc 1
file content3
file content4
abc 2

So you have to explicitly delete them with {/abc 1/d; /abc 2/d;} and then print the rest with p.


With awk:

$ awk '$0=="abc 2" {f=0} f; $0=="abc 1" {f=1}' file
file content3
file content4

It triggers the flag f whenever abc 1 is found and untriggers it when abc 2 is found. f alone will be true and hence print the lines.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top