awk記錄-1
marks.txt
本文件有4列
1) Amit Physics 80
2) Rahul Maths 90
3) Shyam Biology 87
4) Kedar English 85
5) Hari History 89
marks2.txt
本文件有部分列有5列
1) Andy Physics 80 2) Jacky Maths 90 10 3) Hill Biology 87 4) John English 85 12 5) Mary History
b. 樣例
- (1).文本加標題行 "序號 姓名 科目 分數" 顯示:
>awk ‘BEGIN {printf "序號\t姓名\t科目\t分數\n"} {print}‘ marks.txt
序號 姓名 科目 分數 1) Amit Physics 80 2) Rahul Maths 90 3) Shyam Biology 87 4) Kedar English 85 5) Hari History 89
- (2).執行awk腳本:將單引號內的腳本寫到一個文件,然後通過
-f
> cat command.awk BEGIN {printf "序號\t姓名\t科目\t分數\n"} {print}
awk -f command.awk marks.txt
序號 姓名 科目 分數
1) Amit Physics 80
2) Rahul Maths 90
3) Shyam Biology 87
4) Kedar English 85
5) Hari History 89- (3). `-v`聲明一個變量的值,BEGIN前分配
awk -v user=root ‘BEGIN{printf "name=%s\n", user}‘ `
name=root- (4). 計算: + - * / %
awk ‘BEGIN {a=52; b=50; print "a%b=", (a%b)}‘ `
a%b= 2- (5). BEGIN END 定義變量a,在處理行的過程中增加(可以與行內的內容進行計算),END時輸出:(計算總分數)
awk ‘BEGIN { sumScore = 0; printf "總分數sumScore = %d\n", a } {sumScore=sumScore+$NF;print} END{print ">總分數sumScore=",sumScore}‘ marks.txt`
總分數sumScore = 0
1) Amit Physics 80
2) Rahul Maths 90
3) Shyam Biology 87
4) Kedar English 85
5) Hari History 89
總分數sumScore= 431![疲勞的分割線](http://upload-images.jianshu.io/upload_images/3858200-38e21a294ccf66ce.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
awk內置變量: NR
FNR
NF
NR = Number of Records
NF = Number of Fields
FNR = File Number of Records
下面摘自: The GNU Awk User’s Guideawk divides the input for your program into records and fields. It keeps track of the number of records that have been read so far from the current input file. This value is stored in a predefined variable called FNR, which is reset to zero every time a new file is started. Another predefined variable, NR, records the total number of input records read so far from all data files. It starts at zero, but is never automatically reset to zero.
......
The value of the built-in variable NF is the number of fields in the current record.
翻譯與小結:
awk將程序的輸入分為記錄和字段。
它跟蹤從當前輸入文件到目前為止已經讀取的記錄數量。
FNR
該值存儲在一個名為FNR的預定義變量中,每啟動一個新文件時,該變量將重置為零。【每行的行號-單個文件
】
NR
另一個預定義變量NR記錄從所有數據文件中讀取的輸入記錄總數。 它從零開始,但 從不 自動重置為零。【每行的行號-全部文件
】
NF
內置變量NF的值是當前記錄中的字段數。在執行塊中$NF可以得到當前行末字段的值
- (6). 打印全局行號 當前行號 行內列數 行末字段值
> awk ‘BEGIN{print "全局行號\t當前行號\t行內列數\t行末字段值"} {print NR,"\t", FNR,"\t", NF,"\t", $NF}‘ marks.txt marks2.txt
全局行號 當前行號 行內列數 行末字段值
1 1 4 80
2 2 4 90
3 3 4 87
4 4 4 85
5 5 4 89
6 1 4 80
7 2 5 10
8 3 4 87
9 4 5 12
10 5 3 History
![疲勞分割線](http://upload-images.jianshu.io/upload_images/3858200-1ff80eb81fe3ad88.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
awk記錄-1