linux中awk 命令中 NR、FNR内置变量

发布时间 2023-08-17 17:08:12作者: 小鲨鱼2018

 

001、NR

[root@PC1 test02]# cat a.txt        ## 测试文件
1
2
3
4
5
[root@PC1 test02]# cat b.txt        ## 测试文件
11
12
13
14
15
[root@PC1 test02]# awk '{print NR, $0}' a.txt b.txt   ## NR变量,NR将多个文件的行数累积递增
1 1
2 2
3 3
4 4
5 5
6 11
7 12
8 13
9 14
10 15

 

002、FNR

[root@PC1 test02]# cat a.txt
1
2
3
4
5
[root@PC1 test02]# cat b.txt
11
12
13
14
15
[root@PC1 test02]# awk '{print FNR, $0}' a.txt b.txt   ## FNR分别输出多个文件各自的行号
1 1
2 2
3 3
4 4
5 5
1 11
2 12
3 13
4 14
5 15

 

003、应用

[root@PC1 test02]# ls
a.txt  b.txt
[root@PC1 test02]# cat a.txt
1
2
3
4
5
[root@PC1 test02]# cat b.txt
11
12
13
14
15
[root@PC1 test02]# awk 'NR >= 2 && NR <= 4 {print $0}' a.txt b.txt   ## 依据NR进行条件判断
2
3
4

 

004、

[root@PC1 test02]# ls
a.txt  b.txt
[root@PC1 test02]# cat a.txt
1
2
3
4
5
[root@PC1 test02]# cat b.txt
11
12
13
14
15
[root@PC1 test02]# awk 'FNR >= 2 && FNR <= 4 {print $0}' a.txt b.txt  ## FNR的条件判断,实际上是对多个文件同时起作用
2
3
4
12
13
14

 。