The awk of Linux programming

Source: Internet
Author: User
Tags arithmetic operators logical operators modifier

Gawk is a modified awk by the GNU organization, which has a very good application on the Linux operating system and does not require compiling, more than other languages more concise, highly efficient, and able to interact with the shell, is one of the essential editors of the OPS staff.

Gawk is a report generator that reads text into memory, and then the knot matches the display on the screen

Basic syntax for gawk:

gawk [Options] ' program ' File File ...

gawk [Options] ' pattern{action} ' file File ...

1. Output of gawk, using print and printf

Attention:

A, each item is separated by commas, the output uses the output delimiter

b, each item of the output can be a string, a value, a field of the current record, a variable, an expression of gawk

The value is implicitly converted to a string after the output.

C, if the item after print is omitted, it is equivalent to print $; output blank using print ""

Printf:

Use format for commands: printf format,item1,item2,...

Attention:

A, be sure to specify format

b, output, will not automatically wrap, need to join \ n

C, format is used for each item output for the specified formats

The indicator of format begins with%, followed by a modifier

%c: ASCII character for display characters

%d,%i: Integer in decimal

%e,%e: Scientific and technological law shows numerical value

%f: Show floating-point numbers

%s: Display string

%u: Show unsigned integers

Percent: This is an escape, equivalent to% of its own

Modifier

#: Display width, is a numeric value

-: Left-justified display

+: Display symbols for numeric values

. #: Take numeric precision

Built-in variables for gawk:

FS: Field delimiter on input

RS: Enter Yes line delimiter

OFS: Field delimiter at output

ORS: Line delimiter at output

NF: Show Number of fields

NR: Displays the number of lines of the file, if multiple files, together with the harness

FNR: A supplement to NR, counting each file separately

ARVG: An array that holds the command itself

Instance:

Gawk ' {print $} ' file1 file2

Argv[0]:gawk

Argv[1]:file1

ARGC: Save the number of arguments in the gawk command

The above parameter is 3

Filename:gawk the name of the file being processed

This is file1 and file2.

############################################

Custom variables

-V Var_name=value

Variable name Distinguishing character case

Can be defined in the program, or defined in the command line

Instance:

[[email protected] tmp]# gawk-v test= "Hello Linux" ' {print test} '/etc/issue

[[email protected] tmp]# gawk ' {test= "Hello Linux";p rint test} '/etc/issue

The issue here just to provide the number of traversal

##########################################

Gawk Output redirection:

Print Items > Output_file

Print Items >> output_file

Print Items | Command

Special file descriptors

/dev/stdin: Standard input

/dev/stdout: Standard Output

/dev/stderr: Error Output

Instance:

Output users with UID greater than 500 to the common file

[Email protected] tmp]# gawk-f: ' $3>=500{print} '/etc/passwd > Common_user

[[email protected] tmp]# gawk ' BEGIN {"date" | Getline D; Print d} '

#########################################

Gawk operator:

Arithmetic operators

X+y: Add

X-y: Subtract

X*y: Multiply

X/y: Divide

X**y,x^y: Power operation

X%y: modulo operation

-X: Negative value

+x: Convert to Numeric

String operators: Connecting

Negative operator

=

+=

-=

*=

/=

%=

^=,**=

++

Note: If the pattern itself is the = sign, write the/=/

Comparison operators

<

<=

>

>=

==

!=

~: Pattern matching, if the left string can be matched by the pattern on the right, it is true, otherwise false

!~: In contrast to above, indicates that it cannot match

logical operators

&&: Phase

|| : Phase or

Conditional expressions

Selector?if-true-expression:if-false-express

Instance:

# awk-f: ' {$3>=500?utype= ' common user ': utype= "admin or System User";p Rint $, "is", Utype} '

/etc/passwd

Mode:

1, the format is/pattern/

Only rows that are matched to by/pattern/are processed

2, expression, when the result is not 0 or a non-empty string

Only the rows that meet the criteria are processed

3, line range, address delimitation, start_line,stop_line

Processing only the range of rows

4, Begin/end, special mode, run before or after program

Control statements

If-else:

Format: if (condition) (then body) else (else body)

Instance: The/etc/inittab file is displayed with a value greater than 8 fields.

[[email protected] ~]# gawk ' {if (nf>=8) print} '/etc/inittab

While

Format: while (condition) {while body}

[[email protected] ~]# gawk ' {test=1;while (TEST<=NF) {if (length ($test) >=5)

{Print $test};test++}} '/etc/inittab

For

Format: for (variable assignment;condition;itenration process) {for body}

[[email protected] ~]# gawk ' {for (i=1;i<=nf;i+=2) {printf "%s", $i};p rint ""} '/etc/passwd

Next: End the processing of the bank in advance and proceed to the next line

Displays the user name for odd rows, and if there are multiple files, use FNR

[Email protected] ~]# gawk-f: ' {if (nr%2==0) next; print nr,$1} '/etc/passwd

Gawk built-in functions

Split: Cutting

Format: Split (String,array[,fieldsep[,seps])

Function: slices string represented by Fieldsep as a delimiter, and results are saved in array arrays

Array The following table starts from 1

Example: Take out the current time with Gawk, HH:MM:SS

[[Email protected] ~]# Date | Gawk ' {split ($0,arr, "");p rint Arr[4]} '

Length of long string

[Email protected] ~]# echo "Hello World" | Gawk ' {print length} '

Substr

Format: substr (String,start[,length])

Function: Takes a substring from a string, starting from start to a substring that takes length

Instance

[Email protected] ~]# echo "Hello World" | Gawk ' {print (substr ($0,7)} ')

[Email protected] ~]# echo "Hello World" | Gawk ' {print (substr ($0,2,4)} ')


This article is from the "Child Naked Fart" blog, please be sure to keep this source http://cshang.blog.51cto.com/6143980/1565670

The awk of Linux programming

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.