歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> SHELL編程 >> bash shell中expr命令下幾種的使用

bash shell中expr命令下幾種的使用

日期:2017/2/28 15:53:34   编辑:SHELL編程
expr在linux中是一個功能非常強大的命令。通過學習做一個小小的總結。
1、計算字符串的長度。我們可以用awk中的length(s)進行計算。我們也可以用echo中的echo ${#string}進行計算,當然也可以expr中的expr length $string 求出字符串的長度。

舉例

  1. [root@localhost shell]# string="hello,everyone my name is xiaoming"
  2. [root@localhost shell]# echo ${#string}
  3. 34
  4. [root@localhost shell]# expr length "$string"
  5. 34

2、expr中的expr index $string substring索引命令功能在字符串$string上找出substring中字符第一次出現的位置,若找不到則expr index返回0或1。 舉例
  1. [root@localhost shell]# string="hello,everyone my name is xiaoming"
  2. [root@localhost shell]# expr index "$string" my
  3. 11
  4. [root@localhost shell]# expr index "$string" nihao
  5. 1
3、expr中的expr match $string substring命令在string字符串中匹配substring字符串,然後返回匹配到的substring字符串的長度,若找不到則返回0。 舉例
  1. [root@localhost shell]# string="hello,everyone my name is xiaoming"
  2. [root@localhost shell]# expr match "$string" my
  3. 0
  4. [root@localhost shell]# expr match "$string" hell.*
  5. 34
  6. [root@localhost shell]# expr match "$string" hell
  7. 4
  8. [root@localhost shell]# expr match "$string" small
  9. 0
4、在shell中可以用{string:position}和{string:position:length}進行對string字符串中字符的抽取。第一種是從position位置開始抽取直到字符串結束,第二種是從position位置開始抽取長度為length的子串。而用expr中的expr substr $string $position $length同樣能實現上述功能。 舉例
  1. root@localhost shell]# string="hello,everyone my name is xiaoming"
  2. [root@localhost shell]# echo ${string:10}
  3. yone my name is xiaoming
  4. [root@localhost shell]# echo ${string:10:5}
  5. yone
  6. [root@localhost shell]# echo ${string:10:10}
  7. yone my na
  8. [root@localhost shell]# expr substr "$string" 10 5
  9. ryone

注意:echo ${string:10:5}和 expr substr "$string" 10 5的區別在於${string:10:5}以0開始標號而expr substr "$string" 10 5以1開始標號。

5、刪除字符串和抽取字符串相似${string#substring}為刪除string開頭處與substring匹配的最短字符子串,而${string##substring}為刪除string開頭處與substring匹配的最長字符子串。 舉例
  1. [root@localhost shell]# string="20091111 readnow please"
  2. [root@localhost shell]# echo ${string#2*1}
  3. 111 readnow please
  4. [root@localhost shell]# string="20091111 readnow please"
  5. [root@localhost shell]# echo ${string##2*1}
  6. readnow please
解析:第一個為刪除2和1之間最短匹配,第二個為刪除2和1之間的最長匹配。 6、替換子串${string/substring/replacement}表示僅替換一次substring相配字符,而${string//substring//replacement}表示為替換所有的substring相配的子串。 舉例
  1. [root@localhost shell]# string="you and you with me"
  2. [root@localhost shell]# echo ${string/you/me}
  3. me and you with me
  4. [root@localhost shell]# string="you and you with me"
  5. [root@localhost shell]# echo ${string//you/me}
  6. me and me with me
Copyright © Linux教程網 All Rights Reserved