shell 字符串處理

1.獲取字符串長度

    
${#string}
[jason@localhost ~]$ str="hello,world"
[jason@localhost ~]$ echo ${#str}
11

2.獲取子串

${string:position}
${string:position:length}
$(string:(-postion)) 如果使用負數,表示從右開始計數,注意負數必須使用括號

[jason@localhost ~]$ str=ABCDEFGHIJKLMN
[jason@localhost ~]$ echo ${str:1}
BCDEFGHIJKLMN
[jason@localhost ~]$ echo ${str:1:2}
BC
[jason@localhost ~]$ echo ${str:(-2)}
MN

3.子串切除

${string#substring} 從左向右切除最短匹配的子串
${stirng##substring} 從左向右切除最長匹配的子串
${string%substring} 從右向左切除最短匹配的子串
${stirng%%substring} 

4.字符串正則提取

echo $string | grep -oE "regexpression”

[jason@localhost ~]$ str="I am 12 years old"
[jason@localhost ~]$ echo $str | grep -Eo '[0-9]+'
12

5.字符串正則替換

echo $string | sed -r 's/regexpr/replacement'

[jason@localhost ~]$ str="I am 12 years old" 
[jason@localhost ~]$ echo $str | sed -r  "s/ am/'m/"
I'm 12 years old

6.分割字符串

awk

[jason@localhost ~]$ str="I_am_12_years_old, and you?"
[jason@localhost ~]$ echo $str | awk -F '_' '{print $3}'
12
[jason@localhost ~]$ echo $str | awk  '{split($1,a,"_");print a[3]}'
12

7. 獲取索引

awk '{print match($0,"substring")}'

[jason@localhost ~]$ str="I_am_12_years_old, and you?"
[jason@localhost ~]$ echo $str | awk '{print match($0,"[0-9]+")}'
6

注意這個索引是從1開始的

8.sed分組

   sed的分組是很好玩的,在替換模式中,“&”代表前面匹配的全部字符串,而反斜槓加數字表示分組。
[jason@localhost ~]$ str="name:jack;age:12"
[jason@localhost ~]$ echo $str | sed -r 's/name:[^;]+/[&]/'
[name:jack];age:12
[jason@localhost ~]$ echo $str | sed -r 's/name:([^;]+)/--\1--/'
--jack--;age:12

9.awk常用字符串處理函數

sub(reg,replacement,string)
gsub(reg,replacement,string)

將string中匹配正則表達式reg的字符串(全部)替換爲replacement
[jason@localhost ~]$ str="name:jack;age:12"
[jason@localhost ~]$ echo $str | awk '{gsub(/a/,"A",$0);print $0}'      
nAme:jAck;Age:12

index(substring,string) #返回子字符串substring在字符串string中的位置
length(string) #獲取字符串的長度
match(string,reg) #獲取匹配reg得到的子串在字符串中的位置
split(string,array,separator) #將字符串按分隔符separator分割到array數組中
sprintf("format",expression) #和c語言的sprintf類似
substr(string,position,length)  #獲取子字符串
tolower(string)
toupper(string)


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章