標籤:字串
1.由第四個字串開始,截取字串,至字串結束
[[email protected] ~]# myname="Hello myworld"[[email protected] ~]# substr=${myname:3}[[email protected] ~]# echo $substrlo myworld
2.由第6個字串開始,截取8個字元長度的字串
[[email protected] ~]# filename="/root/test.txt"[[email protected] ~]# substr=${filename:6:8}[[email protected] ~]# echo $substrtest.txt
3.取部分位置變數
#! /bin/bashecho $0echo ${@:1} 由第一個位置變數開始,去所有的位置變數執行結果:[[email protected] ~]# ./1.sh 66 77 88 99./1.sh66 77 88 99
4.計算字串長度
[[email protected] ~]# filename="/root/test.txt"[[email protected] ~]# echo ${#filename}14
由字串前面相比,刪除相符者,刪除最短的
[[email protected] ~]# filename="/etc/sysconfig/network-scripts/ifcfg-eth0"[[email protected] ~]# r=${filename#/*/}[[email protected] ~]# echo $rsysconfig/network-scripts/ifcfg-eth0
2.由字串前面相比,刪除相符者,刪除最長的
[[email protected] ~]# filename="/etc/sysconfig/network-scripts/ifcfg-eth0"[[email protected] ~]# r=${filename##/*/}[[email protected] ~]# echo $rifcfg-eth0
3.由字串後面相比,刪除相符者,刪除最短的
[[email protected] ~]# filename="/etc/sysconfig/network-scripts/ifcfg-eth0"[[email protected] ~]# r=${filename%/*}[[email protected] ~]# echo $r/etc/sysconfig/network-scripts
4.有字串後面相比,刪除相符者,刪除最長的
[[email protected] ~]# url="www.baidu.com"[[email protected] ~]# r=${url%%.*}[[email protected] ~]# echo $rwww
文法:${變數/樣式/替換的字串}
只替換第一個符合的字串
[[email protected] ~]# act="root:x:0:0:root:/root:/bin/bash"[[email protected] ~]# r=${act/:/#}[[email protected] ~]# echo $rroot#x:0:0:root:/root:/bin/bash
2.替換所有的符合的字串
[[email protected] ~]# act="root:x:0:0:root:/root:/bin/bash"[[email protected] ~]# r=${act//:/#}[[email protected] ~]# echo $rroot#x#0#0#root#/root#/bin/bash
文法:${變數/樣式}
只刪除第一個符合的字串
[[email protected] ~]# act="root:x:0:0:root:/root:/bin/bash"[[email protected] ~]# r=${act/:/}[[email protected] ~]# echo $rrootx:0:0:root:/root:/bin/bash
2.刪除所有符合的字串
[[email protected] ~]# act="root:x:0:0:root:/root:/bin/bash"[[email protected] ~]# r=${act//:/}[[email protected] ~]# echo $rrootx00root/root/bin/bash
取變數名稱列表
[[email protected] ~]# filename="ifcfg-eth0"[[email protected] ~]# dir="/etc/sysconfig/network-scripts/"[[email protected] ~]# dir_file="$dir/$filename"[[email protected] ~]# echo ${[email protected]}dir dir_file
2.取數組索引列表
[[email protected] ~]# ar=(a b c xy z)
[[email protected] ~]# r=${!ar[@]}
[[email protected] ~]# echo $r
0 1 2 3 4
使用複合命令((算數運算))
使用Bash關鍵詞[[]]組成的式子:[[判斷式]]
[[email protected] ~]# if [[ str > xyz ]];then> echo "字串str比較大"> else> echo "字串str比較小"> fi字串str比較小
3.使用內建命令:test判斷式
本文出自 “Linux革命” 部落格,請務必保留此出處http://kaibinyuan.blog.51cto.com/7304008/1619672
Shell理論學習(四)