The awk command for Linux

Source: Internet
Author: User

Brief introduction

Awk is a powerful text analysis tool, with the search for grep and the editing of SED, which is especially powerful when it comes to analyzing data and generating reports. To put it simply, awk reads the file line-by-row, using spaces as the default delimiter to slice each row, and then perform various analytical processing of the cut.

AWK has 3 different versions: AWK, Nawk, and gawk, which are not specifically described, generally referred to as the GNU version of awk, Gawk,gawk.

Awk has its name from the first letter of its founder Alfred Aho, Peter Weinberger and Brian Kernighan's surname. In fact, Awk does have its own language: The awk programming language, a three-bit creator has formally defined it as "style scanning and processing language." It allows you to create short programs that read input files, sort data, manipulate data, perform calculations on input, and generate reports, as well as countless other features.

How to use

awk ' {pattern + action} ' {filenames}

Although the operation can be complex, the syntax is always the same, where pattern represents what AWK looks for in the data, and the action is a series of commands that are executed when a match is found. Curly braces ({}) do not need to always appear in the program, but they are used to group a series of instructions according to a particular pattern. pattern is the regular expression to be represented, surrounded by slashes.

The most basic function of the awk language is to browse and extract information in a file or string based on the specified rules, before awk extracts the information for additional text operations. A complete awk script is typically used to format the information in a text file.

Typically, awk is treated as a unit of a file's behavior. awk processes the text by executing the corresponding command for each line that receives the file.

Call awk


There are three ways of calling Awk
1. Command-line mode
awk [-F field-separator] ' commands ' input-file (s)
Where commands is the true awk command, [-F domain delimiter] is optional. Input-file (s) is the file to be processed.
In awk, each line in a file, separated by a domain delimiter, is called a domain. In general, the default field delimiter is a space without naming the-F domain delimiter.

2.shell Script Mode
Insert all the awk commands into a file and make the awk program executable, and then awk command interpreter as the first line of the script, again by typing the script name to invoke.
Equivalent to the first line of the shell script: #!/bin/sh
Can be replaced by: #!/bin/awk

3. Insert all the awk commands into a separate file and then invoke:
Awk-f awk-script-file Input-file (s)
Where the-f option loads the awk script in Awk-script-file, Input-file (s) is the same as above.

Here's how to focus on the command line

Getting Started tutorials

1. For example, the output command for Last-n 5 is as follows

Show only the 5 most recently logged-in accounts

#last-N 5 | awk ' {print '} '

The awk workflow is this: reads a record with a ' \ n ' line break, then divides the record by the specified domain delimiter, fills the field, and $ $ represents all fields, representing the first field, $n representing the nth field. The default Domain delimiter is the "blank key" or "[tab] key", so the login user, $ $ means the login user IP, and so on.

2. If only/etc/passwd accounts are displayed

#cat/etc/passwd | Awk-f ': ' {print $} '

Or awk-f ': ' {print '} '/etc/passwd

This is an example of awk+action, where each line executes action{print $.
-f Specifies the domain delimiter as ': '.

3. Display the/etc/passwd account and the corresponding shell of the account, and the TAB key between the account and the shell

#cat/etc/passwd | Awk-f ': ' {print ' \ t ' $7} '

Or awk-f ': ' {print ' \ t ' $7} ' cat/etc/passwd

4. Show the/etc/passwd account and the shell of the account, and the account and the shell are separated by commas, and add the column name Name,shell on all rows, add "Blue,/bin/nosh" on the last line

The awk workflow is done by first executing the beging, then reading the file, reading a record with the/n line break, and then dividing the record by the specified field delimiter, populating the field, and $ $ representing all fields, representing the first field, $n representing the nth field, The action action corresponding to the execution pattern is then started. Then start reading the second record ... Until all the records have been read, the end operation is performed.

5. Search/etc/passwd All rows about the root keyword

# awk-f ': '/root/' cat/etc/passwd

This is an example of the use of pattern, which matches the line of pattern (this is root) to execute the action (without specifying an action, the default output of the contents of each row).
Search support for the regular, for example, root start: awk-f: '/^root/'/etc/passwd

awk built-in variables

Awk has many built-in variables for setting up environment information, which can be changed, and some of the most commonly used variables are given below.

ARGC number of command line arguments
ARGV Command line parameter arrangement
ENVIRON support for the use of system environment variables in queues
FileName awk browses the file name
FNR number of records to browse files
FS sets the input domain delimiter, which is equivalent to the command line-F option
NF browsing the number of fields recorded
NR number of records read
OFS output Field delimiter
ORS Output Record delimiter
RS Control record delimiter

In addition, the $ variable refers to the entire record. $ $ represents the first field of the current row, which is the second field of the current row,...... And so on

1. Statistics/etc/passwd: File name, line number per line, number of columns per row, corresponding full line contents:

#awk-F ': ' {print ' filename: ' filename ', linenumber: ' NR ', columns: ' NF ', linecontent: ' $ '/etc/passwd

2. Use printf instead of print to make your code more concise and easy to read

#awk-F ': ' {printf ("filename:%10s,linenumber:%s,columns:%s,linecontent:%s\n", Filename,nr,nf,$0)} '/etc/passwd

I personally like the printf format

The functions of print and printf two printouts are also available in awk.
The parameters of the print function can be variables, values, or strings. The string must be quoted in double quotation marks, and the arguments are separated by commas. If there are no commas, the parameters are concatenated together and cannot be distinguished. Here, the function of the comma is the same as the delimiter of the output file, except that the latter is a space.
The printf function, whose usage is basically similar to printf in the C language, can format strings, and when the output is complex, printf is more useful and the code more understandable.

AWK programming

Variables and Assignments
In addition to Awk's built-in variables, awk can also customize variables.
1. The following statistics/etc/passwd account number

#awk ' BEGIN {count=0;print ' [Start]user count is ', count} {Count=count+1;print $;} End{print "[End]user Count is", count} '/etc/passwd

Count is a custom variable. The previous action{} has only one print, in fact print is just a statement, and action{} can have more than one statement, separated by a number.

The count is not initialized here, although the default is 0, but the proper approach is initialized to 0:

2. Count the number of bytes occupied by a file under a folder

#ls-L |awk ' BEGIN {size=0;} {size=size+$5;} End{print "[End]size is", size} '

3. If the display is in M:

#ls-L |awk ' BEGIN {size=0;} {size=size+$5;} End{print "[End]size is", size/1024/1024, "M"} '

Note that the statistics do not include subdirectories of folders.

The conditional statement in the

Conditional statement

 awk is drawn from the C language, as shown in the following declaration:
if (expression) {
    statement;
    statement;
    ...
}

if (expression) {
    statement;
} else {
    statement2;
}

if (expression) {
    statement1;
} else if (expression1) {
    Statement2;
} else {
    statement3;
}

Looping statements

The looping statements in awk also draw on the C language, supporting while, Do/while, for, break, continue, which are semantically identical to the semantics of the C language.



Array

Because the subscript of an array in awk can be numbers and letters, the subscript of an array is often referred to as the keyword (key). The values and keywords are stored inside a table for the Key/value application hash. Since hash is not stored sequentially, it is found in the display of array contents, which are not displayed in the order you expect. Arrays, like variables, are created automatically when they are used, and awk automatically determines whether they store numbers or strings. In general, an array in awk is used to collect information from records, which can be used to calculate sums, count words, and how many times the tracking template is matched.



Show/ETC/PASSWD's account

Awk-f ': ' BEGIN {count=0;} {Name[count] = $1;count++;}; End{for (i = 0; i < NR; i++) print I, Name[i]} '/etc/passwd
0 Root
1 daemon
2 bin
3 SYS
4 Sync
5 games
......
This uses the For loop to iterate through the array

The awk command for Linux

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.