Shell常用处理字符串方法(备查)
2013-11-07 11:46
633 查看
一、构造字符串 直接构造 STR_ZERO=hello STR_FIRST="i am a string" STR_SECOND='success' 重复多次 #repeat the first parm($1) by $2 times strRepeat() { local x=$2 if [ "$x" == "" ]; then x=0 fi local STR_TEMP="" while [ $x -ge 1 ]; do STR_TEMP=`printf "%s%s" "$STR_TEMP" "$1"` x=`expr $x - 1` done echo $STR_TEMP } 举例: STR_REPEAT=`strRepeat "$USER_NAME" 3` echo "repeat = $STR_REPEAT" 二、赋值与拷贝 直接赋值 与构造字符串一样 USER_NAME=terry 从变量赋值 ALIASE_NAME=$USER_NAME 三、联接 直接联接两个字符串 STR_TEMP=`printf "%s%s" "$STR_ZERO" "$USER_NAME"` 使用printf可以进行更复杂的联接 四、求长 求字符数(char) COUNT_CHAR=`echo "$STR_FIRST" | wc -m` echo $COUNT_CHAR 求字节数(byte) COUNT_BYTE=`echo "$STR_FIRST" | wc -c` echo $COUNT_BYTE 求字数(word) COUNT_WORD=`echo "$STR_FIRST" | wc -w` echo $COUNT_WORD 五、比较 相等比较 str1 = str2 不等比较 str1 != str2 举例: if [ "$USER_NAME" = "terry" ]; then echo "I am terry" fi 小于比较 #return 0 if the two string is equal, return 1 if $1 < $2, else 2strCompare() { local x=0 if [ "$1" != "$2" ]; then x=2 localTEMP=`printf "%s\n%s" "$1" "$2"` local TEMP2=`(echo "$1"; echo "$2") |sort` if [ "$TEMP" = "$TEMP2" ]; then x=1 fi fi echo $x } 六、测试 判空 -z str 判非空 -n str 是否为数字 # return 0 if the string is num, otherwise 1 strIsNum() { local RET=1 if [ -n "$1" ]; then local STR_TEMP=`echo "$1" | sed 's/[0-9]//g'` if [ -z "$STR_TEMP" ]; then RET=0 fi fi echo $RET } 举例: if [ -n "$USER_NAME" ]; then echo "my name is NOT empty" fi echo `strIsNum "9980"` 七、分割 以符号+为准,将字符分割为左右两部分 使用sed 举例: 命令 date --rfc-3339 seconds 的输出为 2007-04-14 15:09:47+08:00 取其+左边的部分 date --rfc-3339 seconds | sed 's/+[0-9][0-9]:[0-9][0-9]//g' 输出为 2007-04-14 15:09:47 取+右边的部分 date --rfc-3339 seconds | sed 's/.*+//g' 输出为 08:00 以空格为分割符的字符串分割 使用awk 举例: STR_FRUIT="Banana 0.89 100" 取第3字段 echo $STR_FRUIT | awk '{ print $3; }' 八、子字符串 字符串1是否为字符串2的子字符串 # return 0 is $1 is substring of $2, otherwise 1 strIsSubstring() { local x=1 case "$2" in *$1*) x=0;; esac echo $x } 转载:http://www.mcuos.com/thread-2357-1-1.html |
相关文章推荐
- shell if
- shell for while 循环用来一行一行读取文件内容
- Powershell获取当前路径
- 配置NDK时出现:-bash: /home/Administrator/.bash_profile: line 47: syntax error: unexpected .
- shell 判断语句
- -bash: ulimit: max user processes: cannot modify limit: Operation not permitted
- Linux Shell脚本学习
- Adb shell-进入Linux命令行
- linux 环境变量,shell变量
- linux出现bash-3.00的问题
- shell中case的用法学习笔记
- 一个shell for循环与case结合的脚本(监控程序状态)
- shell脚本中case条件控制语句的一个bug分析
- shell编程基础之认识与学习BASH
- linux shell 编程
- linuxshell中"2>&1"含义
- Linuxshell快捷键
- linux shell 中 " if [ ]; ... then ... fi " 的使用
- CentOS6.x下通过shell脚本交互安装Web服务 推荐
- shell中的各种括号