1

I want to build a basic Java class path in a bash script.

This command works out all the jar files to go in my path:

find ~/jars | grep \.jar$

This lists all the jar files I want on my path, one per line.

How can I join together these lines so they are on one line, separated by : and put that into a variable I can use in my script when I invoke Java?

E.g.:

JARS=`find ~/jars | grep \.jar$`
#### somehow make JARS into one line with : between entries
java -cp $JARS ...
4

3 回答 3

2

如果您已经使用过find,则不需要管道。

查找有-regex-name选项,也有printf可用的:

您可以根据您的要求尝试此操作:

find ~/jars -name "*.jar" -printf"%p "

我没有测试,但它会输出所有带有完整路径的罐子,空格分隔。

于 2013-05-06T09:21:00.727 回答
1
jars=($(find ~/jars -type f -name \*.jar))   # save paths into array
classpath=$(IFS=:; echo "${jars[*]}")   # convert to colon-separated
java -cp "$classpath" ...               # and use it
于 2013-05-06T13:06:47.420 回答
1

您可以通过管道传输它并使用 sed 更改新行,

sed ':a;N;$!ba;s/\n/:/g'

全部一起,

find ~/jars | grep \.jar$ | sed ':a;N;$!ba;s/\n/:/g'

您也可以使用 来执行此操作tr,尽管它会留下一个尾随冒号(格伦杰克曼评论):

find ~/jars | grep \.jar$ | tr '\n' ':'

基于SED:如何替换换行符 (\n)?

于 2013-05-06T09:08:34.070 回答