本文用到的测试文件如下:
qingsong@db2a:~$ cat ipa.txt
inet addr:172.17.0.1 Bcast:0.0.0.0 Mask:255.255.0.0
inet addr:192.168.16.128 Bcast:192.168.16.255 Mask:255.255.255.0
inet addr:127.0.0.1 Mask:255.0.0.0
qingsong@db2a:~$ cat ipb.txt
Beth 4.00 0
Dan 3.75 0
Kathy 4.00 10
Mark 5.00 20
Mary 5.50 22
Susie 4.25 18
说明如下:
FNR current record number in FILENAME.
NR current record number in the total input stream.
qingsong@db2a:~$ awk '{print FNR, $0}' ipa.txt ipb.txt
1 inet addr:172.17.0.1 Bcast:0.0.0.0 Mask:255.255.0.0
2 inet addr:192.168.16.128 Bcast:192.168.16.255 Mask:255.255.255.0
3 inet addr:127.0.0.1 Mask:255.0.0.0
1 Beth 4.00 0
2 Dan 3.75 0
3 Kathy 4.00 10
4 Mark 5.00 20
5 Mary 5.50 22
6 Susie 4.25 18
qingsong@db2a:~$ awk '{print NR, $0}' ipa.txt ipb.txt
1 inet addr:172.17.0.1 Bcast:0.0.0.0 Mask:255.255.0.0
2 inet addr:192.168.16.128 Bcast:192.168.16.255 Mask:255.255.255.0
3 inet addr:127.0.0.1 Mask:255.0.0.0
4 Beth 4.00 0
5 Dan 3.75 0
6 Kathy 4.00 10
7 Mark 5.00 20
8 Mary 5.50 22
9 Susie 4.25 18
FS splits records into fields as a regular expression.
OFS inserted between fields on output, initially = " ".
qingsong@db2a:~$ awk '{print $1,$2}' ipb.txt
Beth 4.00
Dan 3.75
Kathy 4.00
Mark 5.00
Mary 5.50
Susie 4.25
qingsong@db2a:~$ awk 'BEGIN {OFS = ":"} {print $1, $2}' ipb.txt
Beth:4.00
Dan:3.75
Kathy:4.00
Mark:5.00
Mary:5.50
Susie:4.25
qingsong@db2a:~$ awk 'BEGIN {FS = "."} {print $1}' ipb.txt
Beth 4
Dan 3
Kathy 4
Mark 5
Mary 5
Susie 4
NF number of fields in the current record.
ORS terminates each record on output, initially = "\n".
RS input record separator, initially = "\n".
qingsong@db2a:~$
关于ORS/RS的应用,我之前写过另一篇文章,如下:
Linux: 文本查找包含某个关键字的段落(awk实现)