Awk multi-row merge (next Introduction) (common application 4)

Source: Internet
Author: User
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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.