Difficult NAWK to Understand
I have not been involved in the UNIX.com shell programming forum for almost a month. Today I received an email reminder from the forum administrator. One of the questions that caught my attention is this nawk one-liner:
I found a command who prints x lines before and after a line who contain a searched string in a text file. The command is :
nawk 'c-->0;$0~s{if(b)for(c=b+1;c>1;c--)print r[(NR-c+1)%b];print;c=a}b{r[NR%b]=$0}' b=2 a=4 s="string" file1
It works very well but I can't understand the syntax, too difficult with "man nawk". Is that some one who will be able to comment this syntax ?
The one-liner is using a lot of shortcut and defaults in the awk code and make it so cryptic. My 'deciphered' version:
nawk -v before=4 -v after=4 -v search="string" ' --current > 0 { print } $0 ~ search{ if ( before ) { for ( current=before+1 ; current>1 ; current-- ) { print rec[(NR-current+1)%before] } } print current=after } before{ rec[NR%before]=$0 }' file1
I think the code is now pretty self-explanatory, hopefully :-)
Labels: awk
0 Comments:
Post a Comment
<< Home