Bash字符串处理(与Java对照) - 12.字符串连接
In Java
String.concat
String concat(String str)
将指定字符串联到此字符串的结尾。
String newStr = str.concat(str2);
StringBuilder.append & StringBuffer.append
推荐使用StringBuilder,而不是StringBuffer。
StringBuilder sb = new StringBuilder();
sb.append("some string").append('c').append(someValue);
String s = sb.toString();
In Bash
将多个字符串变量或者常量合并,在Bash中采用插值的方式
S="$S1$S2"
S="${S1}${S2}"
S="STRING IS $(S1}"
[[email protected] ~]# S1=Hello
[[email protected] ~]# S2=World
[[email protected] ~]# S=$S1$S2
[[email protected] ~]# echo $S
HelloWorld
[[email protected] ~]# S="$S1 $S2"
[[email protected] ~]# echo $S
Hello World
典型应用:在外部命令搜索路径PATH中增加新项
PATH=$PATH:$NEWDIR
[[email protected] ~]# echo $PATH
/usr/kerberos/sbin:/usr/kerberos/bin:/usr/apache/apache-ant-1.7.1/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin
[[email protected] ~]# PATH="$PATH:/usr/games"
[[email protected] ~]# echo $PATH
/usr/kerberos/sbin:/usr/kerberos/bin:/usr/apache/apache-ant-1.7.1/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin:/usr/games
[[email protected] ~]#
在Bash3.1版本及以上,支持+=操作
[[email protected] ~]# echo $PATH
/usr/kerberos/sbin:/usr/kerberos/bin:/usr/apache/apache-ant-1.7.1/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin
[[email protected] ~]# PATH+=":~/bin"
[[email protected] ~]# echo $PATH
/usr/kerberos/sbin:/usr/kerberos/bin:/usr/apache/apache-ant-1.7.1/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin:~/bin
[[email protected] ~]#
本文链接:http://codingstandards.iteye.com/blog/1178681 (转载请注明出处)
返回目录:Java程序员的Bash实用指南系列之字符串处理(目录)
上节内容:Bash字符串处理(与Java对照) - 11.比较两个字符串大小(字典顺序、数值比较)
下节内容:Bash字符串处理(与Java对照) - 13.字符串数组连接(以指定分隔符合并)