shell脚本知识点汇总
sed中在對內(nèi)容進行修改時,有時候需要引用外部變量的值或者獲取一個shell命令執(zhí)行的結(jié)果,以便達到更加可觀的輸出結(jié)果
1、sed中使用變量替換
1)sed命令使用雙引號的情況下,使用$var直接引用
[rooot@192 ~]$ cat test.txt
192.168.53.128/contiv/name
[rooot@192 ~]$ ip=192.168.53.77
[rooot@192 ~]$ sed -i "s/192.168.53.128/$ip/g" test.txt
[rooot@192 ~]$ cat test.txt
192.168.53.77/contiv/name
[rooot@192 ~]$
如果替換的變量內(nèi)容中含有/符號則會提示錯誤,原因是從語法上看,沒有任何問題;但由于變量中包含有“/”作為分隔符,這會和sed的替換操作的分隔符“/”引起混淆;所以,只要不使用“/”做分隔符就可以解決這個問題,如果使用“%”而不是“/”來作為sed的替換操作的分隔符,就不會出錯。其實使用#或%或;作為分隔符也是可以的,只要不會與替換中有相同的而且不是元字符的特殊符號都是可以的
[rooot@192 chenwei]$ path=/home/root
[rooot@192 chenwei]$ cat test.txt
192.168.53.77/contiv/name
[rooot@192 chenwei]$ sed -i "s%192.168.53.77%$path%g" test.txt
[rooot@192 chenwei]$ cat test.txt
/home/root/contiv/name
[rooot@192 chenwei]$ sed -i "s#/home/root#192.168.53.77#g" test.txt
[rooot@192 chenwei]$ cat test.txt
192.168.53.77/contiv/name
[rooot@192 chenwei]$
2)sed命令使用單引號的情況下,使用'"$var"'引用,即變量用雙引號括起來,外面再加上單引號
[rooot@192 chenwei]$ ip=192.168.0.34
[rooot@192 chenwei]$ cat test.txt
192.168.53.77/contiv/name
[rooot@192 chenwei]$ sed -i 's/192.168.53.77/'"$ip"'/g' test.txt
[rooot@192 chenwei]$ cat test.txt
192.168.0.34/contiv/name
[rooot@192 chenwei]$
2、sed中執(zhí)行外部命令
1)sed命令使用單引號的情況下使用'`shell command`'或者'$(shell command)'引用命令執(zhí)行的結(jié)果
[rooot@192 chenwei]$ cat test.txt
192.168.0.34/contiv/name
[rooot@192 chenwei]$ ip=192.168.0.56
[rooot@192 chenwei]$ sed -i 's/192.168.0.34/'`echo $ip`'/g' test.txt
[rooot@192 chenwei]$ cat test.txt
192.168.0.56/contiv/name
[rooot@192 chenwei]$
或者使用新式的命令
[rooot@192 chenwei]$ cat test.txt
192.168.0.56/contiv/name
[rooot@192 chenwei]$ ip=192.168.0.68
[rooot@192 chenwei]$ sed -i 's/192.168.0.56/'$(echo $ip)'/g' test.txt
[rooot@192 chenwei]$ cat test.txt
192.168.0.68/contiv/name
[rooot@192 chenwei]$
2.sed命令使用雙引號的情況下直接`shell command`或者$(shell command)引用命令執(zhí)行的結(jié)果
[rooot@192 chenwei]$ cat test.txt
192.168.0.68/contiv/name
[rooot@192 chenwei]$ ip=192.168.0.56
[rooot@192 chenwei]$ sed -i "s/192.168.0.68/$(echo $ip)/g" test.txt
[rooot@192 chenwei]$ cat test.txt
192.168.0.56/contiv/name
在sed語句里面,變量替換或者執(zhí)行shell命令,雙引號比單引號少繞一些彎子
3、一些小技巧
在每行的頭添加字符,比如"HEAD",命令如下:
sed 's/^/HEAD&/g' test.file
在每行的行尾添加字符,比如“TAIL”,命令如下:
sed 's/$/&TAIL/g' test.file
1)"^"代表行首,"$"代表行尾
2)'s/$/&TAIL/g'中的字符g代表每行出現(xiàn)的字符全部替換,否則只會替換每行第一個,而不繼續(xù)往后找了
4、直接修改文件的內(nèi)容
直接編輯文件選項-i,會匹配test.txt文件中每一行的第一個This替換為this:
sed -i 's/This/this/' test.txt
5、shell變量的寫法
${var} 變量var的值, 與$var相同
echo ${s1}${s2}? ?# 當然這樣寫 $s1$s2 也行,但最好加上大括號??
6、shell支持邏輯與或的寫法
[[]] 表達式
[root@localhost ~]# [ 1 -eq 1 ] && echo 'ok'
ok
[root@localhost ~]$ [[ 2 < 3 ]] && echo 'ok'
ok
[root@localhost ~]$ [[ 2 < 3 && 4 > 5 ]] && echo 'ok'
ok
注意:[[]] 運算符只是[]運算符的擴充。能夠支持<,>符號運算不需要轉(zhuǎn)義符,它還是以字符串比較大小。里面支持邏輯運算符:|| &&
?
轉(zhuǎn)載于:https://www.cnblogs.com/potato-chip/p/9824993.html
總結(jié)
以上是生活随笔為你收集整理的shell脚本知识点汇总的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Pwn-10月21-jarvis-lev
- 下一篇: ATM(BZOJ 1179)