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

5 Answers 5

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).
1
  • I like your answer more than mine.
    – 84104
    Oct 22, 2013 at 17:57
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
1
  • 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, 2020 at 5: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

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 '

2
  • Your second command lacks spaces between the filenames and a terminating newline. Oct 23, 2013 at 1:12
  • @DennisWilliamson Fair point about the lack of space, fixed. Not sure that the newline matters, but it's easy enough to && echo.
    – 84104
    Oct 23, 2013 at 1:50
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.

1
  • Can you add the full command example please?
    – Daniel K
    Apr 19, 2020 at 18:14

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .