Recording learning shell (. 11) for processing an output stream shell

grammar  

awk  [options] [BEGIN] {program} [END] [file]

常用命令选项
-F fs 指定描绘一行中数据字段的文件分隔符  默认为空格
-f file 指定读取程序的文件名
-v var=value 定义awk程序中使用的变量和默认值

注意:awk 程序脚本由左大括号和右大括号定义。脚本命令必须放置在两个大括号之间。由于awk命令行假定脚本是单文本字符串,所以必须将脚本包
括在单引号内。

awk程序运行优先级是:
    1)BEGIN: 在开始处理数据流之前执行,可选项
    2)program: 如何处理数据流,必选项
    3)END: 处理完数据流后执行,可选项

awk basic usage

1. Field extraction: extracting a text and a data printout

   Built-in variables related field

   $ 0 represents the entire line of text

   $ 1 represents the first line of text in a data field

   $ 2 represents the second line of text in the data field

   $ N represents the N lines of text data fields

   $ NF represents the last line of text in the data field

# awk '{print $0}' t.txt
1 the quick brown fox jumps over the lazy dog.
2 the quick brown fox jumps over the lazy dog.
3 the quick brown fox jumps over the lazy dog.
4 the quick brown fox jumps over the lazy dog.

# awk '{print $1}' t.txt
1
2
3
4

# awk '{print $2}' t.txt
the
the
the
the

# awk '{print $3}' t.txt
quick
quick
quick
quick

# awk '{print $NF}' t.txt
dog.
dog.
dog.
dog.

2. How to print a line in a row and a column of it? Use the command NR

# awk 'NR==3{print $0}' t.txt
3 the quick brown fox jumps over the lazy dog.

# awk 'NR==3{print $1}' t.txt
3
# awk 'NR==3{print $2}' t.txt
the

 

3. If the data file is not separated by a space, such as the passwd is to: f separated, if necessary at this time can be used to specify delimiter -F

awk -F ":" 'NR == 1 {print $ 1, $ 3, $ 5}' / etc / passwd # prints the contents of the fifth row of the third line of the first row of the first column passwd file
root 0 root

If you want to change the output format of the above, it can be modified directly print the back part

# Awk -F ":" 'NR == 1 {print $ 1 "-" $ 3 "-" $ 5}' / etc / passwd # 3 between $ 1 $ 5 $ string directly increase
root-0-root

 

4. Print memory usage

# head -3 /proc/meminfo
MemTotal: 2035356 kB
MemFree: 1308408 kB
MemAvailable: 1472264 kB

# head -3 /proc/meminfo | awk 'NR==1{print $2}'

2035356

 

Guess you like

Origin www.cnblogs.com/ruiruiblog/p/12319797.html