1

Using find it is trivial to lookup all files with a particular pattern:

find . -name \*.jar

How do I combine the results of that command (e.g. all of the filenames) into a single string separated by a :?

The expected result would look something like:

"./foo.jar:./bar.jar"

Thank you in advance for your consideration and response.

2

find . -name \*.jar -printf '%P:'

  • You might add | sed 's/:$//' to get rid of the final : or | sed 's/:$/\n/' to have a final newline... – pLumo Sep 12 '18 at 14:43
1
find . -name \*.jar | tr '\n' ':'
0
find . -name '*.jar' | paste -sd : -

But that wouldn't work properly if there were file or directory names that contain newline characters.

To work around that, on a GNU system, you can use:

find . -name '*.jar' -print0 | paste -zsd: | tr '\0' '\n'

Of course, if your file or directory names have : characters, there's not much you can do about it, though you could tell find to skip them:

LC_ALL=C find . -name '*:*' -prune -o -name '*.jar' -print0 |
  paste -zsd: | tr '\0' '\n'

With zsh:

set -o extendedglob # best in ~/.zshrc
jar_files=(**/*.jar~*:*(ND))
printf '%s\n' ${(j/:/)jar_files}
  • I love how you always say : It will not work if there'e new line in your file name. I feel like fs devs should have avoid this to avoid so many troubleshoot. – Kiwy Sep 12 '18 at 14:42
  • it's an excellent point about filenames containing the delimiter, here, though. – Jeff Schaller Sep 12 '18 at 14:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.