开发者

Combine path + list of files to list of absolute files

If I have this data in my shell script:

DIR=/opt/app/classes
JARS=a.jar:b.jar:c.jar

How can I combine this to the string

/opt/app/clas开发者_JAVA技巧ses/a.jar:/opt/app/classes/b.jar:/opt/app/classes/c.jar

in Shell/Bash scripting?


Here's a very short one:

$ echo "$DIR/${JARS//:/:$DIR/}"
/opt/app/classes/a.jar:/opt/app/classes/b.jar:/opt/app/classes/c.jar


If you don't mind an extra semicolon at the end:

[~]> 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:


Use translate and iterate through the results. Then trim the result ':' character at the beginning of the string.

#! /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 :

Result:

/opt/app/classes/a.jar:/opt/app/classes/b.jar:/opt/app/classes/c.jar


Pure Optimized Bash 1-liner

IFS=:; set -- $JARS; for jar; do path+=$DIR/${jar}:; done; echo "$path" 

Output

/opt/app/classes/a.jar:/opt/app/classes/b.jar:/opt/app/classes/c.jar:


Pure Bash, no external utilities:

saveIFS=$IFS
IFS=:
jararr=($JARS)
echo "${jararr[*]/#/$DIR/}"
IFS=saveIFS

Original Answer (before question was revised):

IFS=: read -ra jararr <<<"$JARS"
newarr=(${jararr[@]/#/$DIR/})
echo "${newarr[0]}:${newarr[1]}"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜