awk 常見(jiàn)使用教程
awk 使用的時(shí)候有兩個(gè)要求就是腳本必須放到{}中,由于awk命令假定腳本是單個(gè)文本字符串抡蛙,所以必須將腳本放到單引號(hào)中。
gawk 是Unix 中的原始awk程序的GNU版本 所以 mac 中需要 brew install gawk && echo 'alias awk=gawk' >> ~/.zshrc
gawk '{print "hello world"}' test.txt
gawk
會(huì)對(duì)數(shù)據(jù)流中的每行文本執(zhí)行腳本程序,所以上面的程序結(jié)果是打印和 test.txt 同樣行數(shù)的 hello world
在每個(gè)文本行中,gawk 會(huì)根據(jù) 字段分隔符
給行元素分配變量,默認(rèn)的字段分割符是任意的空白字符,但我們可以通過(guò)參數(shù) -F 設(shè)定肾档。
分配的數(shù)據(jù)字段如下:
- $0 代表整個(gè)文本行
- $1 代表文本行中的第一個(gè)數(shù)據(jù)字段
- $n 代表的事文本行中的第n個(gè)數(shù)據(jù)字段
gawk -F : '{print $1}' /etc/passwd # 在此用冒號(hào)指定為字段分割符
nobody
root
daemon
[...]
gawk 允許你將多條命令組合成一個(gè)正常的程序。命令行之間添加分號(hào)即可, BEGIN
允許你在處理數(shù)據(jù)之前運(yùn)行相關(guān)腳本, END
關(guān)鍵字允許指定一個(gè)腳本程序在 gawk
讀取完數(shù)據(jù)后執(zhí)行辫继。
echo "My name is Rich" | gawk '{$4="test"; print $0}'
My name is test
echo "My name is Rich" | gawk 'BEGIN {print "start"} {$4="test";p
rint $0} END {print "End of File"}'
start
My name is test
End of File
sed 編輯器基礎(chǔ)
Mac 的 sed 是 BSD 版本 注意:brew install gnu-sed --with-default-names
常見(jiàn)替換選項(xiàng)
echo "this is test a test" | sed 's/test/big test/'
this is big test a test
上面的例子使用了 s 命令怒见,s 命令會(huì)用斜線的第二個(gè)文本替換第一個(gè)文本,但我們可以看到只是第一處進(jìn)行了替換姑宽,如果要處理這種問(wèn)題可以使用 替換標(biāo)記
遣耍,有以下四種替換標(biāo)記:
- 數(shù)字,表明新文本將替換第幾處模式匹配的地方炮车。
- g, 表明新文本將會(huì)替換所有匹配的文本舵变。
- p, 表明原先行的內(nèi)容要打印出來(lái),用于顯示模式緩存區(qū)的內(nèi)容
- w file, 將替換的結(jié)果寫入到文件中。
echo "this is test a test" | sed 's/test/big test/g'
this is big test a big test
使用地址
正常情況下 sed 會(huì)作用到文本數(shù)據(jù)的每一行瘦穆,如果只想將命令作用到特定行或者某些行纪隙,需要使用 行尋址
,有以下形式:
數(shù)字方式的行尋址
sed '2s/dog/cat/' test.txt #第二行
sed '2,3s/dog/cat/' test.txt #行地址區(qū)間
sed '2,$s/dog/cat/' test.txt # 從某行開(kāi)始的所有行,使用 $ 符號(hào)標(biāo)記
文本模式過(guò)濾
sed '/wang/s/bash/csh/' /etc/passwd # 前面的 wang 說(shuō)明只處理匹配到該文本的行,當(dāng)然使用正則是最方便扛或。
刪除行
刪除命令 d 可以配合尋址模式進(jìn)行刪除文本
sed '2d' test.txt
插入和附件文本以及修改行
- 插入 (insert) 命令 i 會(huì)在指定行前增加一個(gè)新行
- 附件 (append) 命令 a 會(huì)在指定行后增加一個(gè)新行
- 修改 (change) 命令 c 配合尋址修改行
sed '[address]command\ new line'
sed '1i\this is new line.' test.txt
this is new line.
the quick brown fox
the quick brown fox1
the quick brown fox2
sed '1a\this is new line.' test.txt
the quick brown fox
this is new line.
the quick brown fox1
the quick brown fox2
sed '$a\this is new line.' test.txt # $ 代表最后一行
sed '2c\this is new line.' test.txt
轉(zhuǎn)化命令 y
sed 'y/123/789/' test.txt
the quick brown fox
the quick brown fox7
the quick brown fox8