awk usage record

Introduction to awk

awk is a programming language, used primarily for data processing and text at linux / unix, is a tool in the linux / unix. Standard input data can come from one or more files, or other output commands.
awk way text and data processing: Progressive scan files by default from the first row to the last row, look for the line that matches a particular pattern, and you want to do on these lines.
awk representing the first letter of their last name. Because it was written by three people, namely Aho Alfred, Brian Kernighan, Peter Weinberger
gawk is the GNU version of awk, it provides some extensions Bell Laboratories and the GNU.
Awk described below is an example of the GNU gawk in linux system Yiba link to gawk awk, awk so the following are introduced to all

User's Guide site: https://www.gnu.org/software/gawk/manual/gawk.html

use

Command Mode

awk [options] 'commands' file(s)
    option 部分
        -F 定义字段分割符号,默认的分隔符是空格
        -v 定义变量并赋值
 
    command 部分:
    '范围说明或正则表达式或者{awk命令语句1;awk命令语句2;...}'
 
    'BEGIN{} {}         END{}'
     行处理前      行处理  行处理后
 
    1、范围说明部分可以是BEGIN、END、逻辑表达式或者为空
    2、awk命令语句间用分号间隔
    3、引用shell变量需用双引号引起
 
# 举例:
awk '/root/' /etc/passwd
awk 'NR==1' /etc/passwd
awk 'NR==1{print $1}' /etc/passwd

Script mode

awk [options] -f scriptfile file(s)
特点:
1、awk脚本是awk命令的清单
2、命令需要用分号间隔
3、#号开头的是注释行
4、#!/bin/awk -f 

working principle

# awk -F: '{print $1,$3}' /etc/passwd
(1)awk使用一行作为输入,并将这一行赋给内部变量$0,每一行也可称为一个记录,以换行符(RS)结束

(2)然后,行被:(默认为空格或制表符)分解成字段(或域),每个字段存储在已编号的变量中,从$1开始。

(3)awk如何知道用空格来分隔字段的呢? 因为有一个内部变量FS来确定字段分隔符。初始时,FS赋为空格

(4)awk打印字段时,将以设置的方法使用print函数打印,awk在打印的字段间加上空格,因为$1,$3之间
有一个逗号。逗号比较特殊,它映射为另一个内部变量,称为输出字段分隔符OFS,OFS默认为空格

(5)awk输出之后,将从文件中获取另一行,并将其存储在$0中,覆盖原来的内容,然后将新的字符串分隔
成字段并进行处理。该过程将持续到所有行处理完毕

Basic Application

$0  :表示当前所有记录
$1,$2,$3...$n:awk中用该顺序形式表示files中每行以间隔符号分割的各列的不同字段
注:
awk默认以空格符为间隔符号将每行分割为单独的字段,也可以使用awk内置变量FS定义间隔符号
# awk -F: '{print $1,$7}' a.txt
# awk 'BEGIN{FS=":"} {print $1,$7}' a.txt
 
NF          表示当前记录的字段数(列数)
$NF     最后一列
$(NF-1) 倒数第二列
FNR/NR  行号
FILENAME 文件名
"\t"        制表符
"\n"        换行符
""          打印字符串
FS          定义间隔符,命令里定义。如‘BEGIN{FS=":"}’
OFS         定义"输出字段"的分隔符,默认是空格
RS          输入记录分割符,默认换行(即\n)
ORS         输出记录分割符,默认换行(即\n)
print       打印函数
 
awk -F: 'NR==2{print $1,$(NF-1)}'
 
格式化输出:
print函数     类似echo
# date |awk '{print "Month: "$2 "\nYear: "$NF}'
# awk -F: '{print "username is: " $1 "\t uid is: "$3}' /etc/passwd
 
 
printf函数        类似echo -n
# awk -F: '{printf "%-15s %-10s %-15s\n", $1,$2,$3}'  /etc/passwd
# awk -F: '{printf "|%15s| %10s| %15s|\n", $1,$2,$3}' /etc/passwd
# awk -F: '{printf "|%-15s| %-10s| %-15s|\n", $1,$2,$3}' /etc/passwd
 
%s 字符类型
%d 数值类型
占15字符
- 表示左对齐,默认是右对齐

Guess you like

Origin www.cnblogs.com/CoolMark-blog/p/12237098.html