Navneet Gautam Navneet Gautam - 1 year ago 44
Bash Question

grep a word of some length and pick the n lines below it untill the same length word is found

I have a text file in unix environment containing data and I'm performing some operations on that file using shell script to get some specific data. File data is like this:

USA
11111111111111111111111111
22222222222222222222222222
33333333333333333333333333
UAE
44444444444444444444444444
55555555555555555555555555
77777777777777777777777777
66666666666666666666666666
88888888888888888888888888
USA
99999999999999999999999999
10101010101010101010101010
20202020202020202020202020
50050505050005050505050505
USA
20020202022222020222220202
30303333033030333030303330
UAE
AAAAAAAAAAAAAAAAAAAAAAAAAA
BBBBBBBBBBBBBBBBBBBBBBBBBB
CCCCCCCCCCCCCCCCCCCCCCCCCC
DDDDDDDDDDDDDDDDDDDDDDDDDD
NAE
DDDDDDDDDDDDDDDDDDDDDDDDDD
EEEEEEEEEEEEEEEEEEEEEEEEEE
JJJJJJJJJJJJJJJJJJJJJJJJJJ
KKKKKKKKKKKKKKKKKKKKKKKKKK


I want to get the numbers present below UAEs. i.e. I'm expecting output like this:
Expected Output:

UAE
44444444444444444444444444
55555555555555555555555555
77777777777777777777777777
66666666666666666666666666
88888888888888888888888888
UAE
AAAAAAAAAAAAAAAAAAAAAAAAAA
BBBBBBBBBBBBBBBBBBBBBBBBBB
CCCCCCCCCCCCCCCCCCCCCCCCCC
DDDDDDDDDDDDDDDDDDDDDDDDDD

Answer Source

You may use awk to attain your goal,

$ awk 'length($0)==3{a=($0=="UAE")?1:0}a' file

Brief explanation,

  • Use flag a to determine if a record is printed
  • While length($0)==3, if and only if $0=="UAE", set a=1, otherwise a=0
  • If length($0)!=3, keep what a used to be.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download