Awk multi-line merge [next use introduction] (common application 4)

  
 

When awk performs text processing, we may encounter it. Combine multiple lines into one line to display the problem. A bit like the sql inside, often encountered the problem of row transfer. Here you need to use the next statement.


Awknext statement use: in the loop line by line match, if you encounter next, it will skip the current line, directly ignore the following statement. And the next line is matched.

text.txt Content is:

abcde


[chengmo@centos5 shell]$ awk 'NR%2==1{next}{ Print NR,$0;}' text.txt 2 b4 d

When the record line number is divided by 2 or more 1, the current line is skipped. The following print NR, $0 will not be executed. The next line begins and the program begins to determine the NR%2 value. At this time, the record line number is: 2, and the following statement block will be executed: 'print NR, $0'



awk next use case:

Requirements:

File: text.txt Format: web01[192.168.2.100]

httpd oktomcat oksendmail okweb02[192.168.2.101]httpd okpostfix okweb03[192.168.2.102]mysqld okhttpd ok


The output format needs to be changed by awk:

web01[192.168.2.100]: httpd okweb01[192.168.2.100]: tomcat okweb01[192.168.2.100]: sendmail okweb02 [192.168.2.101]: httpd okweb02[192.168.2.101]: postfix okweb03[192.168.2.102]: mysqld okweb03[192.168.2.102]: httpd ok


Analysis:
< The analysis found that it was necessary to skip the line containing the <quo;web” and then merge the content with the following line into one line.

[chengmo@centos5 shell]$ awk '/^web/{T=$0;next;}{print T":\\t"$0;}' test.txt

web01[ ,null,null,3],192.168.2.100]: httpd okweb01[192.168.2.100]: tomcat okweb01[192.168.2.100]: sendmail okweb02[192.168.2.101]: httpd okweb02[192.168.2.101]: postfix okweb03[192.168.2.102]: mysqld okweb03[192.168. 2.102]: httpd ok


next is very convenient for multi-line merges and selective output. You may wish to try it when you use it.

Copyright © Windows knowledge All Rights Reserved