Shell 编程10(字符串处理)

来源:互联网 发布:linux vim环境配置 编辑:程序博客网 时间:2024/05/17 01:24

字符串处理

之前awk的字符串处理函数, 这次介绍expr命令处理字符串

 

1 计算字符串长度

${#string}  或者 expr length $string

eg

ming@ming-F83VF:~/shellpractice/chapter9$str="Speeding up small jobs in Hadoop"

ming@ming-F83VF:~/shellpractice/chapter9$echo ${#str}

32

ming@ming-F83VF:~/shellpractice/chapter9$expr length "$str"

32


2 索引命令

expr index $string $substring

 

eg

ming@ming-F83VF:~/shellpractice/chapter9$expr index "$str" jobs

13

 

eg

ming@ming-F83VF:~/shellpractice/chapter9$jobs=jobs

ming@ming-F83VF:~/shellpractice/chapter9$expr index "$str" $jobs

13

 

3  抽取子串

#{string:position}       #从名称为$string的字符串的第$position个位置开始抽取子串

#{string:position:length}   #从名称为$string的字符串的第$position个位置开始抽取长度为$length的子串

注意:#{…}格式的命令0开始对名称为$string的字符串进行标号(从左边开始!!!!!)

ming@ming-F83VF:~/shellpractice/chapter9$echo ${str:0}

Speeding up small jobs in Hadoop

ming@ming-F83VF:~/shellpractice/chapter9$echo ${str:10}

p small jobs in Hadoop

ming@ming-F83VF:~/shellpractice/chapter9$echo ${str:10:4}

p sm

ming@ming-F83VF:~/shellpractice/chapter9$echo ${str: -6}

Hadoop

 

#{string: -position}        #冒号和横杠符号之间有一个空格符

#{string:(position)}        #冒号和左括号之间未必要有空格符

从右边开始!!!!!!!!!!!

 

ming@ming-F83VF:~/shellpractice/chapter9$echo ${str: -6}

Hadoop

ming@ming-F83VF:~/shellpractice/chapter9$echo ${str:(-6)}

Hadoop


expr substr $string $position$length   #从名称为$string的字符串的第$position个位置开始抽取长度为$length的子串

注意: expr substr命令是从1开始对名称为$string的字符串进行标号的(上边的是从0开始!!!

 

ming@ming-F83VF:~/shellpractice/chapter9$expr substr "$str" 9 8

 up smal

 

4 删除子串

${string#substring}    #删除string开头处与substring匹配的最短子串

 ${string##substring}  #删除string开头处与substring匹配的最长子串

 ${string%substring}    #删除string结尾处与substring匹配的最短子串

 ${string%%substring}   #删除string结尾处与substring匹配的最长子串

 

eg

定义一个字符串   20121114ReadingHadoop

ming@ming-F83VF:~/shellpractice/chapter9$anotherstr=20121114ReadingHadoop

ming@ming-F83VF:~/shellpractice/chapter9$echo $anotherstr

20121114ReadingHadoop

删除开头处 以 2开始1结尾的  最短字符串!!

ming@ming-F83VF:~/shellpractice/chapter9$echo ${anotherstr#2*1}

21114ReadingHadoop

删除开头处 以 2开始1结尾的  最长字符串!!

ming@ming-F83VF:~/shellpractice/chapter9$echo ${anotherstr##2*1}

4ReadingHadoop

删除结尾处 以 a开始p结尾的  最短字符串!!

ming@ming-F83VF:~/shellpractice/chapter9$echo ${anotherstr%a*p}

20121114ReadingH

删除结尾处 以 a开始p结尾的  最长字符串!!

ming@ming-F83VF:~/shellpractice/chapter9$echo ${anotherstr%%a*p}

20121114Re


5 替换子串

替换子串命令都是${…}格式,可以在任意处、开头处和结尾处替换满足条件的子串

${string/substring/replacement}              #仅替换第一次与substring相匹配的子串

 ${string//substring/replacement}             #替换所有与substring相匹配的子串

${string/#substring/replacement}         #替换string开头处与substring相匹配的子串

 ${string/%substring/replacement}        #替换string结尾处与substring相匹配的子串