- 論壇徽章:
- 0
|
本帖最后由 dream_my_dream 于 2015-05-14 22:21 編輯
1、字段分割
awk '{print "first:" $1 "last:" $4} ' forawk
awk -F ":" '{print "user:" $1 "\tshell:" $7}' forawk
-F參數(shù)設(shè)置的是awk的初始變量FS,F(xiàn)S變量控制著awk的字段分隔符,默認情況下是空白字符。
2、AWK代碼結(jié)構(gòu)
將awk的運行看成3部分組成:處理輸入前的初始化,處理輸入過程,處理完所有輸入后的掃尾工作。BEGIN和END分別映射到第一部分和第三部分。
(1)BEGIN代碼快
awk腳本包含一個BEGIN代碼快,格式是BEGIN標簽加上{}。當腳本很簡單時,使用-F參數(shù)能減少輸入的字符數(shù),但是,當腳本很復(fù)雜時,使用FS參數(shù)清晰的顯示了awk的邏輯。
awk 'BEGIN{FS=":"}{print "user:" $1 "\tshell" $7}' forsed
(2)END代碼快
[root@forshell shell]# cat end
BEGIN{print "how many people with nologin?"}
寫在BEGIN代碼塊中的代碼只在初始化時被運行一次
/nologin/{++adder}
與正則表達式匹配,成功,執(zhí)行++adder
END{print "'nologin' appears "adder" times"}
[root@forshell shell]# awk -f end /etc/passwd
how many people with nologin?
'nologin' appears 25 times
[root@forshell shell]# grep -c nologin /etc/passwd
25
(3) 模式匹配
/正則表達式/ {匹配后執(zhí)行的操作}
[root@forshell shell]# awk -F ":" '/bin\/bash/ {print "hello," $1}' /etc/passwd
hello,root #匹配/bin/bash
hello,pop
hello,ling
awk 'BEGIN{FS=":"} /bin\/bash/ {print "hello," $1}' /etc/passwd
3、變量
變量使用無需先聲明,變量只存儲字符串,當需要時在轉(zhuǎn)換為其他類型
大小寫敏感。局部變量小寫,全局變量帶一個字母大寫,內(nèi)建變量全部大寫。
常用的內(nèi)建變量:
FS:字段分割符,默認為空格 RS:輸出記錄分割字符
OFS:輸出字段分割字符 ORS:輸出記錄分割字符,默認為“\n”
NR:在工作中的記錄數(shù) FNR:當前輸入文件的記錄數(shù)
NF:當前記錄的字段數(shù)
4、格式化輸出
Print:打印整行,輸出到stdout
Printf :將格式化字符串打印到stdout
Sprintf :返回可以賦值給變量的格式化字符串
5、字符串函數(shù)
(1)子字符串查找
index(str,substr) :返回子串在整個串中第一次出現(xiàn)的位置。
函數(shù)字符串開始位置為1,沒有找到子串返回0.
(2)子字符串提取
substr(str,position,[length]):返回str中從position開始的length個字符
[root@forshell shell]# cat info.txt
029-587-49079:Lily
029-587-49081:Kathy
[root@forshell shell]# awk '{print substr($1,5,9)}' info.txt
587-49079
587-49081
(3)字符串匹配
match(str,/reg/):如果在串str中找到正則/reg/匹配的串,則返回出現(xiàn)的位置,未找到則返回0。
與index()的區(qū)別:index()函數(shù)是查找固定字符串的位置,match()支持正則表達式查詢。
(4)子字符串替換
sub(/reg/,replacement,target):只替換第一個匹配字符串。與正則表達式/reg/進行匹配,將target中左邊最長的匹配部分替換成replacement。如果沒有給定target,則默認使用整條記錄。
gsub(/reg/,replacement,target):替換所有匹配的字符串。
# echo "testthisistest test"|awk '{gsub(/test/,"mytest");print}'
mytestthisismytest mytest
#echo "testthisistest test"|awk '{sub(/test/,"mytest");print}'
mytestthisistest test
(5)大小寫轉(zhuǎn)換
toupper(str):對字符串進行大小寫轉(zhuǎn)換
tolower(str):對字符串進行大小寫轉(zhuǎn)換
|
|