nakeer
nakeer

Reputation: 767

How to get the file name from a list of files

So heres the scenario:

I need to write an automated script which picks the jar file from a directory. But the jar file will be replaced with a new jar file at regular intervals

eg: XXX/YYY/server-sdk-01.00.00-000080.000055.e0eb521.jar

the server-sdk part is constant all the time but the rest of the version numbering changes.

How can I read the file name and save it to a variable in this scenario.

I tried

fspec=XXX/YYY/server-sdk-*.jar 

filename="${fspec##*/}"  # get filename
dirname="${fspec%/*}" # get directory/path name

But here I only get server-sdk-*.jar as the filename where I expect it to be server-sdk-01.00.00-000080.000055.e0eb521.jar.

Upvotes: 1

Views: 78

Answers (2)

Tim Pierce
Tim Pierce

Reputation: 5664

The short answer is to use echo to force filename expansion:

fspec=$(echo XXX/YYY/server-sdk-*.jar)

In the event that there is more than one server-sdk-*.jar file in this directory, you can do this to select only the newest one:

fspec=$(ls -t XXX/YYY/server-sdk-*.jar | head -1)

Upvotes: 0

anubhava
anubhava

Reputation: 784908

Double command substitunion to rescue here for shell expansion. Consider this script

> set +f
> fspec=XXX/YYY/server-sdk-*.jar
> f=$(echo $(echo "$fspec"))
> echo "$f"
XXX/YYY/server-sdk-01.00.00-000080.000055.e0eb521.jar

> filename="${f##*/}"
> echo "$filename"
server-sdk-01.00.00-000080.000055.e0eb521.jar
> dirname="${f%/*}"
> echo "$dirname"
XXX/YYY

Upvotes: 1

Related Questions