2012年8月28日 星期二

shell script - awk,cut,tr,sed

awk - 可以用來分隔字串
例:
-F:分隔符號delimiter
ex:
root@yuan-laptop:~# echo A,B,C | awk -F ',' '{ print $1"-"$2"-"$3}'
A-B-C

cut - 每行分割字串
-c 計算幾個位元
-d 分隔符號
-fn 取第n個被分隔符號分割的字串
ex:
root@yuan-laptop:~# echo 192.168.1.100 | cut -c 5-7
168
root@yuan-laptop:~# echo 192.168.1.100 | cut -d '.' -f 1
192
root@yuan-laptop:~# echo 192.168.1.100 | cut -d '.' -f 1,3,4
192.1.100
root@yuan-laptop:~# echo 192.168.1.100 | cut -d '.' -f 3-4
1.100

tr - 每行刪除或取代

ex:
1.小寫變大寫
root@yuan-laptop:~# echo ABCxyz | tr [a-z] [A-Z]
ABCXYZ

2.刪除'.'
root@yuan-laptop:~# echo 192.168.1.100 |tr -d '.'
1921681100

3.取代
root@yuan-laptop:~# echo 192.168.1.100 |tr -s '.' '-'
192-168-1-100

sed - 新增刪除取代,印出特定行數
-n 將stdin的訊息不印出,只印出sed處理過得字串
p列印
例如:
列印出第1-2行的資料
root@yuan-laptop:~# cat /etc/passwd | sed -n '1,2p'
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/bin/sh

綜合運用
1.取MAC address
ifconfig eth2 | sed -n '1p' | awk -F' ' '{print $5}'

2.取IP address
ifconfig eth2 | grep 'inet addr' | awk -F':' '{print $2}'| cut -d ' ' -f1



沒有留言: