Case six: awk awk treatment according to the conditions of insert text

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

The compiler environment

   This series of articles provide algorithms in the following compiler environment through.

[The script compiler environment] Federa 8, Linux 2.6.35.6-45.fc14.i686
[] Intel processor (R) Core (TM) 2 Quad CPU Q9400 @ 2.66GHz
[memory] 2025272 kB

Preface

    Awk is a text processing tools excellent script. The source code is written in C language. This series will for different case, use awk to solve the problems we have to. Why awk? Of course we can use the C language or Java language to text processing, but every time you compile a crazy. Revise up trouble, is the so-called break a butterfly. While the script is flexible and convenient makes the work easier. In the shell script programming, awk is a Swiss Army knife will not be excessive.

    This series of articles were written by the author, there are some mistakes or errors, if friends have good suggestions or better algorithms, please generous with your criticism.

The text

[The scene]

   There is now a text a.txt as follows:

1
2
333
44
222
44

   After c.txt extraction, text contents are as follows:

1
555
2
333
555
44
222
44

[Code]

BEGIN {
   FS="[ ]+"
}
{
      a[NR]=$0
}
/44/{
      a[NR-2] = "555\n"a[NR-2]
}
END {
   for(i=1; i<=NR;i++)
   {
      print a[i]
   }
}

[Interpretation]

   In awk, pattern and {in the same line. Like BEGIN and END in the same line.

   When the traversal of the awk, can not modify the text, so the text stored in the array.

Author

   Source:

   In this paper, the copyright belongs to the author, welcome to reprint, but without the permission of the author must keep this statement, and the connection in the article page is the obvious position, or retain the right to pursue legal responsibilities.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Amanda at November 09, 2013 - 2:53 AM