天天看點

Linux Shell之cut和awk(字元串的切割)

1. 我想擷取下面配置檔案(abc.txt)中的第一行的值

canal.instance.master.address = 172.16.116.134:3306
canal.instance.master.journal.name = mysql-bin.000001
canal.instance.master.position = 120
canal.instance.master.timestamp =
           

2. 指令如下

grep canal.instance.master.address abc.txt | cut -d = -f 2
           

3. 得到的結果

172.16.116.134:3306
           

4. 可以看到前面有個空格,我們把空格去掉,隻需再輸出一下

echo `grep canal.instance.master.address abc.txt | cut -d = -f 2`
           

5. 最終結果

172.16.116.134:3306
           

6. 分析:cut -d = -f 2

-d 的意思是:--delimiter,分界符,使用指定分界符代替制表符作為區域分界。是以 -d = 的意思就是以等号為分割點

-f 的意思是:--fields,選哪個域。是以  -f 2的意思是選分割後的第二列

7. 缺點:cut的分界符隻能為單位元組

// 假如test.log中的内容為: abc==def
// 以雙等于号為分割點
cat test.log |cut -d == -f 2
// 報錯
cut: the delimiter must be a single character
           

8. awk 完美的字元串分割指令,針對7中的文本

// 用雙等于号進行分割
cat test.log | awk -F '==' '{print $1}'
// 我們也可以周遊分割的結果, 或者在for循環中進行結果處理
cat test.log | awk -F '==' '{for(i=1;i<=NF;i++){print $i}}'
// 我們可以先用==分割, 然後再用字母e分割
cat test.log | awk -F '[==|e]' '{for(i=1;i<=NF;i++){print $i}}'