Shell 字符串常见操作
参考文章:http://blog.csdn.net/chen_jp/article/details/8922582
一 字符替换
origin=原字符串 str=替换后的字符串
替换命令:
str=${origin//目标字符/替换后的字符}
例如:
str=${origin//:/_}
代码示例:
origin='mark:x:0:0:this is a test user:/var/mark:nologin' str=${origin//:/_} echo ${origin} echo ${str}
输出:
mark:x:0:0:this is a test user:/var/mark:nologin mark_x_0_0_this is a test user_/var/mark_nologin
二 字符串分割
origin='mark:x:0:0:this is a test user:/var/mark:nologin' i=1 while((1==1)) do split=`echo $origin|cut -d ":" -f$i` if [ "$split" != "" ] then ((i++)) echo $split else break fi done
输出:
mark x 0 0 this is a test user /var/mark nologin