[Musketeers] awk command

Foreword

awk is a great language, it is suitable for text processing and report generation.

The syntax is more common, draws some of the best in some languages, such as C language.

In daily processing Linux system, play a very important role, mastered the awk will make your work become tall.

 

1. awk combat explain

1.1 awk principle

Through a simple command, let's see how it works.

awk '{print $0}' /etc/passwd
echo hhh|awk '{print "hello,world"}'
awk '{print "hiya"}' /etc/passwd

Output:

[root@oldboy /]# awk '{print $0}' /etc/passwd
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
...
stu06:x:831:831::/home/stu06:/bin/bash
stu07:x:832:832::/home/stu07:/bin/bash
stu08:x:833:833::/home/stu08:/bin/bash
stu09:x:834:834::/home/stu09:/bin/bash
stu10:x:835:835::/home/stu10:/bin/bash


[root@oldboy /]# echo hhh|awk '{print "hello,world"}'  
hello,world


[rootAttooldboy /] # awk '{print "hiya"}' / etc / passwd 
hiya 
hiya 
... 

hiya 
hiya 
hiya 
hiya 
hiya 
# Rows sum / etc / passwd manner Rows equality
awk examples

By way of example above, explanation awk done:

  • When calling awk, we specified / etc / passwd file as input.
  • When executed awk, it evaluated the print command to / etc / passwd each row.
  • All outputs are sent to stdout, the results obtained with the implementation of cat / etc / passwd identical.

 

Now, explanation {print} code block:

  • In awk, curly braces {} are grouped together the blocks of code, which is similar to the C language.
  • In only one code block print command. In awk, if a print command appears, then print the entire contents of the current line.

 

Again, awk implementation of the script for each row in the input file:

 

 1.2 BEGIN and END module

Typically, for each input line, awk code block will be executed once for each script.

However, in many cases become, you may need to perform the initialization code before awk begins processing the text file.

In this case, awk allows to define a BEGIN block.

awk starts processing the input file before the BEGIN block, therefore, it is initialized FS (field separator) variable, heading, or initialize the print position to other global variables will be used later in the program.

 

awk also provides another special block, called the END block.

awk END block will execute after all lines in the input file.

Typically, END block for performing calculation or the final print summary information should appear in the output end of the stream.

 

Operators 1.3

 

Guess you like

Origin www.cnblogs.com/zoe233/p/11923734.html