awk笔记

本文围绕awk命令展开,介绍了其多种使用方式,如按特定格式输出文件内容、进行数值计算与统计等。还提及了awk中的内置变量,如NF、NR等,以及数组操作、字符串处理函数等,最后给出了一个统计空行的示例及相关参考链接。

awk -F":" '{ print "username: " $1 "/t/tuid:" $3 }' /etc/passwd

awk 'FS=":" {OFS="-"} {print NR "-->" $1, $2}' /etc/passwd

awk '{x=x+$3} {print NR, $3, x}' data
awk '{x=x+$3} END {print NR, $3, x}' data

awk '{x=x+$3} {print NR, $3, x | "sort -nr"}' data

FS="[[:space:]+]"

       NF          The number of fields in the current input record.
       NR          The total number of input records seen so far.
       OFMT        The output format for numbers, "%.6g", by default.
       OFS         The output field separator, a space by default.
       ORS         The output record separator, by default a newline.

awk中数组从1开始

for ( x in myarray ) {
    print myarray[x]
}
当 awk 在数组下标之间轮转时,它不会依照任何特定的顺序

delete fooarray[1]

print length(mystring)

print index(mystring,"you")

print tolower(mystring)
print toupper(mystring)
print mystring // unchanged

mysub=substr(mystring,startpos,maxlen)

print match(mystring,/you/), RSTART, RLENGTH
RSTART 包含返回值(第一个匹配的位置),RLENGTH 指定它占据的字符跨度(如果没有找到匹配,则返回 -1)。

sub(regexp,replstring,mystring)
sub() 将替换第一个 regexp 匹配(如果有的话),gsub() 将执行全局替换

numelements=split("Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec",mymonths,",")


test.awk
---------
BEGIN   { x=0 }
/^$/    { x=x+1 }
END     { print "I found " x " blank lines. :)" }
---------------
awk -f test.awk inputfile

摘录自:
http://www-128.ibm.com/developerworks/cn/linux/shell/awk/awk-1/index.html
http://www-128.ibm.com/developerworks/cn/linux/shell/awk/awk-2/index.html
http://www-128.ibm.com/developerworks/cn/linux/shell/awk/awk-3/index.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值