LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   how to delete lines according to a pattern in awk (https://www.linuxquestions.org/questions/programming-9/how-to-delete-lines-according-to-a-pattern-in-awk-925793/)

Massimo34 01-26-2012 09:08 AM

how to delete lines according to a pattern in awk
 
I need to delete(or skip) next three lines after a pattern is found in some line of the file.
Does anybpdy have an idea how to do that in awk?

thanks

catkin 01-26-2012 09:35 AM

Use the getline function three times

firstfire 01-26-2012 11:54 AM

Hi.

If you don't mind using sed,
Code:

$ echo -e '1\n2\n3\n4\n5\n6' | sed '/2/{n;N;N;d}'
1
2
6

From `man sed':
Quote:

n N Read/append the next line of input into the pattern space.
d Delete pattern space. Start next cycle.
If you replace `n' by `N', the line with a pattern will also be removed.
In GNU sed the latter can be done also as follows
Code:

$ echo -e '1\n2\n3\n4\n5\n6' | sed '/2/,+3 d'
1
6


grail 01-26-2012 12:40 PM

Record NR value plus 3 at point of finding what you want and only print more details when you get to corresponding NR value

Nominal Animal 01-26-2012 03:19 PM

Human languages are sometimes frustratingly vague. You thought you stated your desire accurately, but there are four solutions with different results that all do what you stated you want.

If you want to keep the line containing the matching pattern, but omit the three next lines, use
Code:

awk '          { print }
    /pattern/ { getline ; getline ; getline ; next }
    ' input-file > output-file

which uses getline three times like Catkin said. The three lines are completely ignored. In particular, the script does not check if the pattern matches in the deleted lines. Therefore, if you have the pattern on four consecutive lines, only three lines are omitted.

If you want to the three lines including the one containing the pattern, use
Code:

awk '/pattern/ { getline ; getline ; getline ; next }
              { print }
    ' input-file > output-file

In this case, if you have three consecutive lines containing the pattern, they are all omitted, but the immediately following line not containing the pattern will be included.

If you want to check if the omitted lines trigger further omissions, use Grail's approach:
Code:

awk '/pattern/ { nNR = NR + 3 }
            NR >= nNR { print }
    ' input-file > output-file

If you want the omission to omit the three lines that follow it, but not the triggering line itself (unless that line is omitted due to a prior match), use
Code:

awk '      NR >= nNR { print }
    /pattern/ { nNR = NR + 4 }
    ' input-file > output-file

I recommend you test the above with different types of input, not just the one you expect to receive, and pick the one that matches your needs.


All times are GMT -5. The time now is 07:02 PM.