(1)AWK快速入门

awk用法入门

awk 'awk_program' a.txt

 awk示例:

[root@docker-01 ~]# awk '{print $0}' a.txt  # 输出a.txt中的每一行
ID  name    gender  age  email          phone
1   Bob     male    28   [email protected]     18023394012
2   Alice   female  24   [email protected]  18084925203
3   Tony    male    21   aaa@163.com    17048792503
4   Kevin   male    21   bbb@189.com    17023929033
5   Alex    male    18   [email protected]    18185904230
6   Andy    female  22   ddd@139.com    18923902352
7   Jerry   female  25   exdsa@189.com  18785234906
8   Peter   male    20   [email protected]     17729348758
9   Steven  female  23   [email protected]    15947893212
10  Bruce   female  27   bcbd@139.com   13942943905
[root@docker-01 ~]# awk '{print $0}{print "hello";print "world"}' a.txt
ID  name    gender  age  email          phone
hello
world
1   Bob     male    28   [email protected]     18023394012
hello
world
2   Alice   female  24   [email protected]  18084925203
hello
world
3   Tony    male    21   aaa@163.com    17048792503
hello
world
4   Kevin   male    21   bbb@189.com    17023929033
hello
world
5   Alex    male    18   [email protected]    18185904230
hello
world
6   Andy    female  22   ddd@139.com    18923902352
hello
world
7   Jerry   female  25   exdsa@189.com  18785234906
hello
world
8   Peter   male    20   [email protected]     17729348758
hello
world
9   Steven  female  23   [email protected]    15947893212
hello
world
10  Bruce   female  27   bcbd@139.com   13942943905
hello
world
# 多个代码块,代码块中多个语句
# 输出每行之后还输出两行:hello行和world行

对于awk '{print $0}' a.txt,它类似于shell的while循环while read line;do echo "$line";done <a.txt。awk隐藏了读取每一行的while循环,它会自动读取每一行,其中的{print $0}对应于Shell的while循环体echo "$line"部分。

下面再分析该awk命令的执行过程:

  1. 读取文件第一行(awk默认按行读取文件)
  2. 将所读取的行赋值给awk的变量$0,于是$0中保存的就是本次所读取的行数据
  3. 进入代码块{print $0}并执行其中代码print $0,即输出$0,也即输出当前所读取的行
  4. 执行完本次代码之后,进入下一轮awk循环:继续读取下一行(第二行)
    • 将第二行赋值给变量$0
    • 进入代码块执行print $0
    • 执行完代码块后再次进入下一轮awk循环,即读取第三行,然后赋值给$0,再执行代码块
    • ...不断循环,直到读完文件所有数据...
  5. 退出awk

猜你喜欢

转载自www.cnblogs.com/liujunjun/p/12388894.html
今日推荐