简体   繁体   中英

Using sed to print lines between 2 patterns

I have a file that looks like this:

Index: <filepath>
===================================================================
<lines to print>
<lines to print>
<lines to print>
Index: <filepath>
===================================================================
<lines to print>
<lines to print>
<lines to print>
... and so on

I need to print the line starting with Index: skip the line containing ====== and print all other lines until the next instance of Index:

The filepath will be different each time, so I need a command that will match the Index: part and print that whole line.

I have been trying to use the sed command but I can't seem to get it to print the lines I want. Is there a way I can do this?

expected output:

Index: <filepath>
<lines to print>
<lines to print>
<lines to print>

You can use this awk :

awk '/^Index:/{p=!p} p && !/^====/' file

Index: <filepath>
<lines to print>
<lines to print>
<lines to print>

Details:

  • /^Index:/{p=!p} : When we find Index: at the start set a flag p or reset it (toggle effect by using p=!p )
  • p && !/^====/ If flag p is 1 and we don't have ==== at the start of a record then print the record.

If you want to print next Index: line also then use:

awk '/^Index:/{if (p) print; p=!p} p && !/^====/' file

I came up to this command

sed -n '1,/^Index:/{/^Index:/!d;}; /^Index:/{x;/^$/!p;n;n;}; H; ${g;p;};'
  • It deletes from start till the first Index: line
  • Then it saves into a holding buffer everything from Index: till next Index: excluding ======= line, which is assumed to follow Index: immediately
  • When Index: line is met, it prints the content of the holding buffer if it's not empty
  • When the end of the file reached it prints the content of the holding buffer

     $ cat /tmp/test First line Index: <filepath> =================================================================== <lines to print> <lines to print> <lines to print> Index: <filepath> =================================================================== <lines to print> <lines to print> <lines to print> $ sed -n '1,/^Index:/{/^Index:/!d;}; /^Index:/{x;/^$/!p;n;n;}; H; ${g;p;};' \\ /tmp/test Index: <filepath> <lines to print> <lines to print> <lines to print> Index: <filepath> <lines to print> <lines to print> <lines to print> 

    But as David mentioned, it can be shorten and then it's just a simple

     sed '1,/^Index:/{/^Index:/!d;}; /^=/d;' /tmp/test 

which is just the same for lines before the first Index and then just removing lines starting with =

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM