We may encounter this problem during awk text processing. Merge multiple rows into one row for display. This is a bit like SQL, which often causes row-to-column conversion. The next statement is required here.
Use the awknext statement: This statement matches rows by row in a loop. if next is encountered, the current row is skipped and the following statement is ignored. And match the next line.
Copy codeThe code is as follows:
The text.txt content is:
A
B
C
D
E
[Chengmo @ centos5 shell] $ awk 'NR % 2 = 1 {next} {print NR, $0;} 'text.txt
2 B
4 d
When the record row number is divided by more than 2 1, the current row is skipped. The following print NR, $0 will not be executed. Starting from the next line, the program starts to judge the value of NR % 2. When the record row number is: 2, the following statement block will be executed: 'Print NR, $0'
Examples of awk next usage:
Copy codeThe 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
Httpd OK
You need to convert the output format:
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:
The analysis shows that the "web" line must be skipped, and the content and the following line must be merged into one row.
[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
Next is very convenient in multi-row merge and selective output. You may try it when using it.