First, the environment
ubuntu14.04 x86_64
Second, string manipulation
1. get the string length
Strlen () similar to the C language
${#variable_name}
Eg:
$name =zhangsan$echo ${#name}8$
2. String Extraction
Similar to substring () in Java
${variable_name:start_index:length} from left to right , starting with section Start_index (0), the length of the substring
${variable_name:0-start_pos:length} Starting from the end the number of Start_pos, length of the substring
eg
$echo ${name:0:4}zhang$echo ${name:2} #从第二个位置开始, to the end Angsan$echo ${name:0-4:2}gs$echo ${name:0-4} #从倒数第4开始, to the end
3. String interception
Delete from left to right
${variable_name#*separator} separator is the character you want to separate, to the position of the first separator
STRCHR () similar to the C language
eg
$name =zhangsan-lisi-wangwu-baidi$echo ${name#*-}lisi-wangwu-baidi$
${variable_name##*separator} to the last separator position.
Rindex () similar to the C language
eg
$echo ${name##*-}baidi$
Delete from right to left
${variable_name%separator*}
${variable_name%%separator*}
eg
$echo ${name%-*} Zhangsan-lisi-wangwu$echo ${name%%-*}zhangsan$
4. String splitting
C language-like strtok ()
${variable_name//ch/ch_replace} replaces the character ch in variable_name with the ch_replace character
eg
$name =zhangsan-lisi-wangwu-baidi$name=${name//-/,} #将横杠替换为逗号 $echo ${name}zhangsan,lisi,wangwu,baidi$name={name// ,/} #将逗号替换为空格 $echo ${name}zhangsan Lisi Wangwu Baidi #可用于后续的for循环 $
IFS is split by setting the value of IFS
eg
$test =aaa,bbb,ccc,ddd,eee$arr=${test} $echo ${arr}aaa,bbb,ccc,ddd,eee$old_ifs= $IFS $ifs=, $arr 2=${test} $echo ${arr2 }AAA BBB CCC DDD Eee$ifs=${old_ifs}
This article is from the "Snow Dancer" blog, please be sure to keep this source http://happytree007.blog.51cto.com/6335296/1904950
Shell string manipulation