When it comes to command line text processing, from an abstract point of view, there are three major pillars



Download 125.91 Kb.
Page48/60
Date09.03.2023
Size125.91 Kb.
#60849
1   ...   44   45   46   47   48   49   50   51   ...   60
Learn GNU AWK

Specific blocks


Instead of working with all the groups (or blocks) bound by the markers, this section will discuss how to choose blocks based on additional criteria.
Here's how you can process only the first matching block.
$ awk '/start/{f=1} f; /end/{exit}' uniform.txt --start 1-- 1234 6789 **end 1** $ # use other tricks discussed in previous section as needed $ awk '/end/{exit} f; /start/{f=1}' uniform.txt 1234 6789
Getting last block alone involves lot more work, unless you happen to know how many blocks are present in the input file.
$ # reverse input linewise, change the order of comparison, reverse again $ # can't be used if RS has to be something other than newline $ tac uniform.txt | awk '/end/{f=1} f; /start/{exit}' | tac --start 2-- a b c **end 2** $ # or, save the blocks in a buffer and print the last one alone $ awk '/start/{f=1; b=$0; next} f{b=b ORS $0} /end/{f=0} END{print b}' uniform.txt --start 2-- a b c **end 2**
Only the nth block.
$ # can also use: awk -v n=2 '/4/{c++} c==n{print; if(/6/) exit}' $ seq 30 | awk -v n=2 '/4/{c++} c==n; /6/ && c==n{exit}' 14 15 16
All blocks greater than nth block.
$ seq 30 | awk -v n=1 '/4/{f=1; c++} f && c>n; /6/{f=0}' 14 15 16 24 25 26
Excluding nth block.
$ seq 30 | awk -v n=2 '/4/{f=1; c++} f && c!=n; /6/{f=0}' 4 5 6 24 25 26
All blocks, only if the records between the markers match an additional condition.
$ # additional condition here is a record with entire content as '15' $ seq 30 | awk '/4/{f=1; buf=$0; m=0; next} f{buf=buf ORS $0} /6/{f=0; if(m) print buf} $0=="15"{m=1}' 14 15 16

Broken blocks


Sometimes, you can have markers in random order and mixed in different ways. In such cases, to work with blocks without any other marker present in between them, the buffer approach comes in handy again.
$ cat broken.txt qqqqqqqqqqqqqqqq error 1 hi error 2 1234 6789 state 1 bye state 2 error 3 xyz error 4 abcd state 3 zzzzzzzzzzzzzzzz $ awk '/error/{f=1; buf=$0; next} f{buf=buf ORS $0} /state/{if(f) print buf; f=0}' broken.txt error 2 1234 6789 state 1 error 4 abcd state 3

Download 125.91 Kb.

Share with your friends:
1   ...   44   45   46   47   48   49   50   51   ...   60




The database is protected by copyright ©ininet.org 2024
send message

    Main page