1. 程式人生 > >shell指令碼知識點彙總

shell指令碼知識點彙總

sed中在對內容進行修改時,有時候需要引用外部變數的值或者獲取一個shell命令執行的結果,以便達到更加可觀的輸出結果

1、sed中使用變數替換
1)sed命令使用雙引號的情況下,使用$var直接引用
[[email protected] ~]$ cat test.txt
192.168.53.128/contiv/name
[[email protected] ~]$ ip=192.168.53.77
[[email protected] ~]$ sed -i "s/192.168.53.128/$ip/g" test.txt
[[email protected] ~]$ cat test.txt
192.168.53.77/contiv/name
[

[email protected] ~]$
如果替換的變數內容中含有/符號則會提示錯誤,原因是從語法上看,沒有任何問題;但由於變數中包含有“/”作為分隔符,這會和sed的替換操作的分隔符“/”引起混淆;所以,只要不使用“/”做分隔符就可以解決這個問題,如果使用“%”而不是“/”來作為sed的替換操作的分隔符,就不會出錯。其實使用#或%或;作為分隔符也是可以的,只要不會與替換中有相同的而且不是元字元的特殊符號都是可以的
[[email protected] chenwei]$ path=/home/root
[[email protected] chenwei]$ cat test.txt
192.168.53.77/contiv/name
[
[email protected]
chenwei]$ sed -i "s%192.168.53.77%$path%g" test.txt
[[email protected] chenwei]$ cat test.txt
/home/root/contiv/name
[[email protected] chenwei]$ sed -i "s#/home/root#192.168.53.77#g" test.txt
[[email protected] chenwei]$ cat test.txt
192.168.53.77/contiv/name
[[email protected]
chenwei]$
2)sed命令使用單引號的情況下,使用'"$var"'引用,即變數用雙引號括起來,外面再加上單引號
[[email protected] chenwei]$ ip=192.168.0.34
[[email protected] chenwei]$ cat test.txt
192.168.53.77/contiv/name
[[email protected] chenwei]$ sed -i 's/192.168.53.77/'"$ip"'/g' test.txt
[[email protected] chenwei]$ cat test.txt
192.168.0.34/contiv/name
[[email protected] chenwei]$

2、sed中執行外部命令
1)sed命令使用單引號的情況下使用'`shell command`'或者'$(shell command)'引用命令執行的結果
[[email protected] chenwei]$ cat test.txt
192.168.0.34/contiv/name
[[email protected] chenwei]$ ip=192.168.0.56
[[email protected] chenwei]$ sed -i 's/192.168.0.34/'`echo $ip`'/g' test.txt
[[email protected] chenwei]$ cat test.txt
192.168.0.56/contiv/name
[[email protected] chenwei]$
或者使用新式的命令
[[email protected] chenwei]$ cat test.txt
192.168.0.56/contiv/name
[[email protected] chenwei]$ ip=192.168.0.68
[[email protected] chenwei]$ sed -i 's/192.168.0.56/'$(echo $ip)'/g' test.txt
[[email protected] chenwei]$ cat test.txt
192.168.0.68/contiv/name
[[email protected] chenwei]$
2.sed命令使用雙引號的情況下直接`shell command`或者$(shell command)引用命令執行的結果
[[email protected] chenwei]$ cat test.txt
192.168.0.68/contiv/name
[[email protected] chenwei]$ ip=192.168.0.56
[[email protected] chenwei]$ sed -i "s/192.168.0.68/$(echo $ip)/g" test.txt
[[email protected] chenwei]$ cat test.txt
192.168.0.56/contiv/name

在sed語句裡面,變數替換或者執行shell命令,雙引號比單引號少繞一些彎子

3、一些小技巧

在每行的頭新增字元,比如"HEAD",命令如下:
sed 's/^/HEAD&/g' test.file
在每行的行尾新增字元,比如“TAIL”,命令如下:
sed 's/$/&TAIL/g' test.file
1)"^"代表行首,"$"代表行尾
2)'s/$/&TAIL/g'中的字元g代表每行出現的字元全部替換,否則只會替換每行第一個,而不繼續往後找了

4、直接修改檔案的內容

直接編輯檔案選項-i,會匹配test.txt檔案中每一行的第一個This替換為this:
sed -i 's/This/this/' test.txt

5、shell變數的寫法

${var} 變數var的值, 與$var相同

echo ${s1}${s2}   # 當然這樣寫 $s1$s2 也行,但最好加上大括號  

6、shell支援邏輯與或的寫法

[[]] 表示式
[[email protected] ~]# [ 1 -eq 1 ] && echo 'ok'
ok
[[email protected] ~]$ [[ 2 < 3 ]] && echo 'ok'
ok

[[email protected] ~]$ [[ 2 < 3 && 4 > 5 ]] && echo 'ok'
ok
注意:[[]] 運算子只是[]運算子的擴充。能夠支援<,>符號運算不需要轉義符,它還是以字串比較大小。裡面支援邏輯運算子:|| &&