Home > Back-end >  Remove multiple lines from a given match until an empty line
Remove multiple lines from a given match until an empty line

Time:11-07

On a unix system I have a file and I need to remove all lines that would match Package: <PKG_NAME> until an empty line is found. Here is an example, I would need to remove terminfo information:

...
Package: kmod-usb-storage
Version: 5.4.218-1
Depends: kernel (= 5.4.218-1-0c02597a113d34441a9bfe9294e3fb84), kmod-scsi-core, kmod-usb-core
Status: install user installed
Architecture: mips_24kc
Installed-Time: 1667822688
Auto-Installed: yes

Package: terminfo
Version: 6.2-1
Depends: libc
Status: install user installed
Architecture: mips_24kc
Installed-Time: 1667816896

Package: libuci-lua
Version: 2020-10-06-52bbc99f-5
Depends: libc, libuci20130104, liblua5.1.5
Status: install user installed
Architecture: mips_24kc
Installed-Time: 1667816896
Auto-Installed: yes
...

Afterwards I need to have no information about terminfo:

...
Package: kmod-usb-storage
Version: 5.4.218-1
Depends: kernel (= 5.4.218-1-0c02597a113d34441a9bfe9294e3fb84), kmod-scsi-core, kmod-usb-core
Status: install user installed
Architecture: mips_24kc
Installed-Time: 1667822688
Auto-Installed: yes

Package: libuci-lua
Version: 2020-10-06-52bbc99f-5
Depends: libc, libuci20130104, liblua5.1.5
Status: install user installed
Architecture: mips_24kc
Installed-Time: 1667816896
Auto-Installed: yes
...

I would be using this functionality inside a shell script, I have tried using sed and awk with no useful results, I couldn't figure out this problem.

CodePudding user response:

You can probably get away with:

 awk '!/terminfo/' RS= ORS='\n\n' 

Setting RS to the empty string causes awk to treat each section as a record ("section" meaning chunk of text delimited by an empty line, often called a "paragraph"), so you just print the ones that don't match the string terminfo. To be more precise, you might want to use:

awk '!/^Package: terminfo/' RS= ORS='\n\n'

but that doesn't seem necessary.

CodePudding user response:

You can also use sed '/terminfo/,/^$/d'. This will delete from a line containing terminfo till an empty line is found.

See How to print lines between two patterns, inclusive or exclusive (in sed, AWK or Perl)? for more such problems dealing with multiple lines.

  • Related