如果我在shell脚本中有这些数据:
DIR=/opt/app/classes
JARS=a.jar:b.jar:c.jar
如何将其与字符串
组合/opt/app/classes/a.jar:/opt/app/classes/b.jar:/opt/app/classes/c.jar
Shell / Bash脚本中的?
答案 0 :(得分:10)
这是一个很短的一个:
$ echo "$DIR/${JARS//:/:$DIR/}"
/opt/app/classes/a.jar:/opt/app/classes/b.jar:/opt/app/classes/c.jar
答案 1 :(得分:0)
如果你不介意最后加一个分号:
[~]> for a in `echo $JARS | tr ":" "\n"`;do echo -n $DIR/$a:;done&&echo
/opt/app/classes/a.jar:/opt/app/classes/b.jar:/opt/app/classes/c.jar:
答案 2 :(得分:0)
使用翻译并迭代结果。然后修剪字符串开头的结果':'字符。
#! /bin/bash
DIR=/opt/app/classes
JARS=a.jar:b.jar:c.jar
for i in $(echo $JARS | tr ":" "\n")
do
result=$result:$DIR/$i
done
echo ${result#:} // Remove the starting :
结果:
/opt/app/classes/a.jar:/opt/app/classes/b.jar:/opt/app/classes/c.jar
答案 3 :(得分:0)
Pure Bash,没有外部工具:
saveIFS=$IFS
IFS=:
jararr=($JARS)
echo "${jararr[*]/#/$DIR/}"
IFS=saveIFS
原始答案(在问题修订之前):
IFS=: read -ra jararr <<<"$JARS"
newarr=(${jararr[@]/#/$DIR/})
echo "${newarr[0]}:${newarr[1]}"
答案 4 :(得分:0)
Pure Optimized Bash 1-liner
IFS=:; set -- $JARS; for jar; do path+=$DIR/${jar}:; done; echo "$path"
/opt/app/classes/a.jar:/opt/app/classes/b.jar:/opt/app/classes/c.jar: