现在的位置: 首页 > 综合 > 正文

awk技巧

2018年03月16日 ⁄ 综合 ⁄ 共 954字 ⁄ 字号 评论关闭

1通过awk脚本运行awk程序:awk-f program_file_name input_files

#!/bin/awk -f
BEGIN
{
    print "What is your name,sir?";
    while(getline>0)
        print "Hi",$1,"Nice to meet you!"
}

2 FILENAME, FNR

awk '{print FILENAME, FNR;}' student-marks bookdetails

student-marks 1
student-marks 2
student-marks 3
student-marks 4
student-marks 5
bookdetails 1
bookdetails 2
bookdetails 3
bookdetails 4
bookdetails 5

3 倒序输出文本 

awk '{line[NR]=$0} END{i=NR;while(i>0) {print line[i];i=i-1}} ' readme.tx

4 获取给定月份的最后一个星期六的日期

cal 04 2012 | awk '{ print $7 }' | grep -v "^$" | tail -1

5 重要的变量

NR:Nubmer of records

FNR:Number of records(different with files)

NF:Number of fields,separate by FS

FS:Field separator, space or Tab by default

OFS: Output field separator, space by default

ORS: Output record separator,same as RS

6 丰富的内置函数

gsub(r,s) substitute s for r globally in $0 return number of substitution made


更多内容:

1http://coolshell.cn/articles/9070.html

2http://www.thegeekstuff.com/2010/01/8-powerful-awk-built-in-variables-fs-ofs-rs-ors-nr-nf-filename-fnr/

3http://web.cs.du.edu/~dconnors/courses/comp2400/notes/AWK.pdf

抱歉!评论已关闭.