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 ...
Will
  • 73,905
  • 40
  • 169
  • 246

3 Answers3

2

if you have already used find, you don't need the pipe.

find has -regex and -name option, also has printf available:

You could try this for your requirement:

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

I didn't test, but it would output all jars with full path, space separated.

Kent
  • 189,393
  • 32
  • 233
  • 301
  • Good one! Also, would it be possible to have a couple of downvotes for tag suggestions? I want to cancel two I suggested in http://stackoverflow.com/tags/synonyms?filter=suggested : bash-alias and commands-unix – fedorqui May 06 '13 at 09:24
  • @fedorqui I don't even know SO has this function. :D no idea how to do it.. sorry. – Kent May 06 '13 at 09:27
  • Haha, just go to http://stackoverflow.com/tags/bash/synonyms and http://stackoverflow.com/tags/unix/synonyms and up/downvote. If you want, of course! Everything is explained in http://stackoverflow.com/privileges/suggest-tag-synonyms – fedorqui May 06 '13 at 09:29
1

You can pipe it and with sed change new line for ,:

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

All together,

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

You can also do it with tr, although it leaves a trailing colon (glenn jackman comment):

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

Based on SED: How can I replace a newline (\n)?

Community
  • 1
  • 1
fedorqui
  • 275,237
  • 103
  • 548
  • 598
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
glenn jackman
  • 238,783
  • 38
  • 220
  • 352