Remove a set of rows from a file separated by a white line having a specific key word

前端 未结 2 795
刺人心
刺人心 2021-01-17 07:07

I have a file containing lines as given below. I want to delete a set of rows from the file, if any line from a set of rows contains key word SEDS2-TOP. Each set of rows is

2条回答
  •  无人共我
    2021-01-17 07:37

    separated by a white line should lead you to paragraph mode.

    Perl:

    $ perl -00 -ne 'print if !/SEDS2-TOP/' sample.txt
    0.00  600.00  2214.28   785.71 1.00000 SEDS1-BOTTOM
    0.00  600.00  2214.28   785.71 1.00000 SEDS1-TOP
    0.00  600.00  1500.00     0.00 1.00000 WATER-BOTTOM
    
    0.00  400.00  2004.28   785.71 1.00000 SEDS1-BOTTOM
    0.00  300.00  2254.28   785.71 1.00000 SEDS1-TOP
    0.00  600.00  1600.00     0.00 1.00000 WATER-BOTTOM
    
    • -00 enable paragraph mode
    • -n don't print by default
    • print if !/SEDS2-TOP/ - print paragraph only if it doesn't match

    AWK variant:

    $ awk -v RS= -v ORS='\n\n' '!/SEDS2-TOP/' sample.txt
    
    0.00  600.00  2214.28   785.71 1.00000 SEDS1-BOTTOM
    0.00  600.00  2214.28   785.71 1.00000 SEDS1-TOP
    0.00  600.00  1500.00     0.00 1.00000 WATER-BOTTOM
    
    0.00  400.00  2004.28   785.71 1.00000 SEDS1-BOTTOM
    0.00  300.00  2254.28   785.71 1.00000 SEDS1-TOP
    0.00  600.00  1600.00     0.00 1.00000 WATER-BOTTOM
    
    • -v RS= - enable paragraph mode
    • -v ORS='\n\n'- separate output with one new line
    • !/SEDS2-TOP/ - print only if the paragraph doesn't match

    A cumbersome approach to "move" the matching records into a new file would be:

    perl -00 -i -ne 'if (!/SEDS2-TOP/) { print } else {print STDERR}' sample.txt 2>sample2.txt
    
    • -i modifies sample.txt in place
    • print STDERR - will print non matching lines into on STDERR
    • 2>sample2.txt - saves the STDERR into the new file.

    However, that requires in-place editing and not many textutils have that. Easiest approach is to create two new files, ones with the mathing records and one with non matching ones.

    awk -v RS= -v ORS='\n\n' '!/SEDS2-TOP/' sample.txt >not_maching.txt
    awk -v RS= -v ORS='\n\n' '/SEDS2-TOP/' sample.txt  >matching.txt
    

提交回复
热议问题