Linux uses awk to implement multi-line merge instances

  
                

In the Linux system using awk text processing tools, sometimes need to merge multiple lines, which requires the use of awknext statement, the following small series will introduce you to the use of awk in Linux to achieve multi-line merge method, the need Friends can come to understand.

awknext statements use: Progressive match in circulation, if they are next, will skip the current line, simply ignore the following statement. And the next line is matched.

The code is as follows:

The text.txt content is:

a

b

c

d< Br>

e

[chengmo@centos5 shell]$ awk ‘NR%2==1{next}{print NR,$0;}’ text.txt

2 b

4 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:

The code is as follows:

Requirements:

File: text.txt Format:

web01[192.168.2.100]

httpd ok

tomcat ok

sendmail Ok

web02[192.168.2.101]

httpd ok

postfix ok

web03[192.168.2.102]

mysqld ok< Br>

httpd ok

The output format needs to be changed by awk:

web01[192.168.2.100]: httpd ok

web01[192.168.2.100]: Tomcat ok

web01[192.168.2.100]: sendmail ok

web02[192.168.2.101]: httpd ok

web02[192.168.2.101]: postfix ok

web03[192.168.2.102]: mysqld ok

web03[192.168.2.102]: httpd ok

Analysis:

Analysis needs to include "<quo;web&rdquo Go Skip, then you need to 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[192.168.2.100]: httpd ok

web01[192.168.2.100]: tomcat ok

web01[192.168.2.100]: sendmail ok

web02[192.168.2.101 ]: httpd ok

web02[192.168.2.101]: postfix ok

web03[192.168.2.102]: mysqld ok

web03[192.168.2.102]: httpd ok< Br>

The above is the introduction of Linux using awk for multi-line merging. It is very convenient to use the next statement in the text. In the loop matching, if you encounter next, it will automatically skip, thus achieving multi-line merging. .

Copyright © Windows knowledge All Rights Reserved