awk,sed是shell里最常用的分隔字符串的命令
但是对于不可见字符(\n,\r,\t),对于特殊字符(?,*,#,$)做分割符,操作比较困难
而且获取结果不方便,
因此我写了个分割函数支持
1.各种不可见字符(\n,\r,\t),对于特殊字符(?,*,#,$),任意长度的分隔符
2.返回结果为数组
代码如下:
- #!/bin/bash
- #分割字符串函数
- #参数1 split_argv1:要分割的字符串
- #参数2 split_argv2:分隔符
- #返回值:0:成功,1:失败;
- #结果集:split_array数组
- #
- split_str(){
- if [ "$split_argv2" == "" ]
- then
- return 1;
- fi
- split_len=0;
- split_array=();
- break_len=${#split_argv2}
- #判断是否包含分隔符,获取索引
- index=`expr index "$split_argv1" "$split_argv2"`
- while [[ "$index" -gt "0" ]]
- do
- #获得分割好的字符串
- split_array[$split_len]=${split_argv1:0:$index-1}
- split_len=$split_len+1;
- #记录截断的字符串
- split_argv1=${split_argv1:$index-1+break_len}
- index=`expr index "$split_argv1" "$split_argv2"`
- done
- #把最后一个保存
- split_array[$split_len]=$split_argv1;
- return 0;
- }
- echo "------------------------------------------------------------------"
- split_argv1=$1;
- split_argv2=$2;
- echo "argv1=[$1]"
- echo "argv2=[$2]"
- #测试
- split_str $1 $2
- #打印结果
- alen=${#split_array[*]};
- echo -n "result="
- for ((i=0;i< $alen;i++))
- do
- echo -n "["${split_array[$i]}"],";
- done
- echo "";
- echo "------------------------------------------------------------------"
- exit 0;
运行结果
- ------------------------------------------------------------------
- [root@localhost cgi-bin]# sh split_str.sh "1*2*3*4" "*"
- ------------------------------------------------------------------
- argv1=[1*2*3*4]
- argv2=[*]
- result=[1],[2],[3],[4],
- ------------------------------------------------------------------
- [root@localhost cgi-bin]# sh split_str.sh "a
- b
- c
- d" "
- "
- ------------------------------------------------------------------
- argv1=[a
- b
- c
- d]
- argv2=[
- ]
- result=[a],[b],[c],[d],
- ------------------------------------------------------------------
- [root@localhost cgi-bin]# sh split_str.sh "1abc23 abcd4" "abc"
- ------------------------------------------------------------------
- argv1=[1abc23 abcd4]
- argv2=[abc]
- result=[1],[23 ],[d4],
- ------------------------------------------------------------------
end
阅读(2046) | 评论(0) | 转发(0) |