shell script -awk

A, awk works

 

Two, awk usage

 awk [the Option] ... 'Program' FILE ...
    1, Program statement must use single quotes!
    2, a plurality of program statements used together with curly braces, can be parallel, can be nested
three, awk common parameters

 -F # specify the delimiter

 Example: awk -F: The first column is the delimiter: '{print $ 1}' / etc / passwd # output / etc / passwd / file in

   

   -v # because awk is a language compiler, you can define their own variables, but also has its own built-in variables (variables and the shell ring similar), so to manually specify variable parameters.

 Example: awk -va = "a + b" '{print a}' test.txt # to a copy, print a variable (variable does not need to call in awk added $ symbol)

  

 

Four, awk's syntax

 1.print # default output

  In the awk command is not saved, we can associate other awk command to save the results of

  示例:awk '{a="a+b";print a}' test.txt | tee a.txt

  

 2.printf # achieve formatted output

  Example: printf "% s% d is the best class for" variable 1, variable 2

  (1) character format

       String% s
            % d% i value
            % e% E scientific calculation value
            % c ACSii code value
            % f float
            % u unsigned integer
            %%% escape character only display their

    (2) Modifiers

    The default is right-aligned

    - on behalf of Left

    Median% 5.4f # 5 representatives share, taken on behalf of 4 decimal places

  3. Variables

  Variables into built-in variables and custom variables

  Built-in variables are variables awk language supported by default

  variable:

    FS # delimiter defining input variables

    OFS # define the output variable delimiter

    NF # line separator after the number of parameters defined (the last one variable partition after $ NF)

  Example: awk -v FS = ":" '/ \ / bash $ / {print $ 1, $ NF}' / etc / passwd    

 

            File number of rows NR definition file, define multiple files, line numbers superimposed
            FNR file count only their own line number

  Example: awk '{print NR}' / etc / fstab / etc / passwd

 
            awk '{print FNR}' /etc/fstab /etc/passwd 

  

      FILENAME name of the file is stored

   Example: awk '{print FILENAME}' / etc / passwd # N times to print the file name, the file number of rows N

  

  BEGIN {} while statement cycle start line only performed once;

  Example: awk 'BEGIN {print FILENAME}' / etc / passwd

  

Guess you like

Origin www.cnblogs.com/hmm01031007/p/11402609.html