AWK里面的NR、NF用法

1.NF:支持记录域个数,在记录被读之后再设置1

[root@redhat wilsontest]# pwd

/tmp/wilsontest

[root@redhat wilsontest]# echo $PWD | awk -F / '{print $NF}'

wilsontest

这里取得的是当前目录的最后一个文件的名字。

再如:

[root@redhat wilsontest]# echo "/usr/local/etc/rc.sybase" | awk -F / '{print $NF}'

rc.sybase

-F /表示以’/’分开域


2.NR:已经读取的记录数 3.FILENAME

定义:支持awk脚本实际操作的输入文件。因为awk可以同时处理许多文件,因此如果访问了这个变量,将告之系统目前正在浏览的实际文件。

例如:

[root@redhat wilsontest]# cat filetest

hello wilson

world

linux

oracle

C++

[root@redhat wilsontest]# awk '{print NF,NR,$0}END{print FILENAME}' filetest

2 1 hello wilson

1 2 world

1 3 linux

1 4 oracle

1 5 C++

说明:

第一列NF输出读取记录的域的个数;

NR表示已经读取的记录数;

$0实际就是把记录输出出来;

$0就表示一个记录,$1表示记录中的第一个字段。
一般 print $0 就是打印整行内容($0前面不需要反斜杠),print $1表示只打印每行第一个字段。

FILENAME就是输出正在处理的文件。


为了说明FILENAME的作用,再做如下操作:

[root@redhat wilsontest]# cp filetest filetest.bak

[root@redhat wilsontest]# ls -la

total 28

drwxr-xr-x  2 root root 4096 Oct 26 10:02 .

drwxrwxrwt 11 root root 4096 Oct 26 09:46 ..

-rw-r--r--  1 root root   36 Oct 26 10:00 filetest

-rw-r--r--  1 root root   36 Oct 26 10:02 filetest.bak

-rw-r--r--  1 root root 4617 Oct 23 09:10 man.config

[root@redhat wilsontest]# awk '{print NF,NR,$0}END{print FILENAME}' filetest filetest.bak

2 1 hello wilson

1 2 world

1 3 linux

1 4 oracle

1 5 C++

2 6 hello wilson

1 7 world

1 8 linux

1 9 oracle

1 10 C++

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值