0

I have a folder called lib. In that folder are some files. I want to obtain all the names of the files that end in .jar, and concatenate them into a line, separated by spaces. I don't want the path name at all.

I've tried this:

ls lib/*.jar | xargs

and the output is

lib/file1.jar lib/file2.jar

But what I'm trying to get is

file1.jar file2.jar

How can I do this?

I've also tried find but I get the same problem

find lib -name *.jar | xargs
Steve McLeod
  • 190
  • 1
  • 1
  • 10

5 Answers5

3

And another find lib -maxdepth 1 -name *.jar -printf '%f\n' | xargs

          %f     File's  name  with any leading directories removed (only
                 the last element).
Mark Wagner
  • 18,019
  • 2
  • 32
  • 47
1

This worked for me, though it seems there should be an easier (i.e. less hackish and prettier) way:

$ ls lib/*.jar | xargs -n 1 basename | xargs
John
  • 9,070
  • 1
  • 29
  • 34
  • For my purposes, this was simple enough and worked fine- I just dropped the last pipe to xargs to get my list with a newline after each result. – Rajib Sep 21 '20 at 05:24
1

Just to show that you can achieve the same in different ways: If you use bash, you can do:

for i in lib/*.jar; do echo ${i#*/}; done|xargs

or

echo $(for i in lib/*.jar; do echo ${i#*/}; done)

0

Old question, but if you're going to use find it would be better to just use -exec rather than piping to xargs. That way the original problem's solved because there's no need to remove the path from the filename.

Peter
  • 1
0

basename from coreutils is an option.
find lib -maxdepth 1 -name *.jar -exec basename {} \; | xargs


Blatantly ripped from Mark Wagner, but without the extra call to xargs.
find lib -maxdepth 1 -name *.jar -printf '%f '

84104
  • 12,905
  • 6
  • 45
  • 76