Shell 字符串操作

  在做shell批处理操作的时候,经常会涉及字符串相关操作,有很多操作命令,如awk,sed都可以做字符串的操作,其实shell内置一系列操作符号,可以达到类似效果,而且使用内部操作符会省略启动外部程序等时间,因此速度很快

判断读取字符串的值

${var}:变量var的值,与$var相同

${var-default}:如果变量没有声明,那么就以$default作为其值

${var:-default}:若变量没有声明或者其值为空,则$default作为其值

${var+other}:若变量声明了,那么其值就是$other,否则为null字符串

${var:+other}:若变量被设置了,那么其值就是$other,否则为null字符串

${var?err_msg}:若变量没声明,那么就打印$err_msg

${var:?err_msg}:若变量没被设置,那么就打印$err_msg

${!varprefix*}:匹配之前所有以varprefix开头进行声明的变量

${!varprefix@}:匹配之前所有以varprefix开头进行声明的变量

#!/bin/sh

name='yang'
DEFAULT='default_yang'
OTHER='other_yang'
ERR_MSG='ERR_yang'

echo ${name}
echo ${name1-$DEFAULT}
echo ${name2:-$DEFAULT}

echo ${name+$OTHER}
echo ${name:+$OTHER}

echo ${name?$ERR_MSG}
echo ${name:?$ERR_MSG}

echo ${!name*}
echo ${!name@}

字符串操作

${#string}:$string的长度

${string:position}:对string从位置position开始截取子串

${string:position:length}:对string从位置position截取长度为length的子串

${string#substring}:从string的开头,删除最短匹配subtring的子串

${string##substring}:从string开头,删除最长匹配substring的子串

${string%substring}:从string结尾,删除最短匹配substring的子串

${string%%substring}:从string结尾,删除最长匹配substring的子串

${string/substring/replacement}:使用replacement替换第一个匹配的substring

${string//substring/replacement}:使用replacement替换所有匹配的substring

${string/#substring/replacement}:如果string的前缀跟substring匹配,就用replacement来替换匹配到的substring

${string/%substring/replacement}:如果string的前缀跟substring匹配,就用replacement来替换匹配到的substring

#!/bin/sh

string='hello/hello/world/hello/python/hello/programming/programming'

echo 'string: '$string

echo ${#string}

echo ${string:10}
echo ${string:10:5}
echo ''


substring1='*/'
substring2='/*'
echo ${string#$substring1}
echo ${string##$substring1}
echo ${string%$substring2}
echo ${string%%$substring2}
echo ''

replacement1='*/'
replacement2='/*'
echo ${string/hello//$replacement1}
echo ${string//hello//$replacement1}
echo ${string/#hello//$replacement1}
echo ${string/%/programming/$replacement2}  

性能比较

在shell在可以通过awk,sed等命令实现

速度相差百倍,调用外部命令,与内置操作符性能相差相当大,在shell编程中,尽量使用内置操作符和函数操作,使用awk,sed会出现相似的效果

转载

原文地址:https://www.cnblogs.com/yyf573462811/p/9592960.html