[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 993
  • Last Modified:

UNIX scripting - ksh - get part of filename as valiable


Would like to see somebody's help on writing small ksh script runs on UNIX.

Environment : Solaris 8/10
in one directory say /var/tmp , there are multiple files in below manner.
i.e. abc_20110501 , abc_20110502, abc_20110503

I would like to get "latest file's filename , only date part, for this case,   only for "20110503"
within ksh script.

Would somebody kindly help?
2 Solutions
cd /var/tmp
file=$(ls abc*)
echo ${file#*_}

Open in new window

Small correction

file=$(ls abc*)

Open in new window

should be

file=$(ls -t abc*)

Open in new window

assuming you're basing the latest file on modification date.
Tintin's soln assumes that the timestamps on the file are matching the timestamps in filename. Without that it won't work. E.g. if you transfer the files to a different place.

Use this if you really want to sort by the timestamp given in the file name:
// assuming YYYYMMDD format:
LATEST_DATE=`ls -1 /var/tmp/abc_* | sed 's/abc_//' | sort | tail -1`
// or you can use cut as well if the prefix is fixed length (always abc_)
LATEST_DATE=`ls -1 /var/tmp/abc_* | cut -b 5- | sort | tail -1`

Open in new window

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Gerwin Jansen, EE MVETopic Advisor Commented:
LATEST_DATE=`ls -1tr abc_* | tail -1 | cut -d"_" -f2`


ls -1tr abc_*
# list all abc_* files in 1 column, sorted by date, most recent file last

tail -1
# get only last file = most recent file

cut -d"_" -f2
# cut string at _ and print 2nd part (date
sleepinglukeAuthor Commented:
thanks all for helpful tips and knowledges!
I could workout with theKashyap second command as date should be fixed length for a time being.

Note that you don't need ls's "-1" switch in this context (i.e. just "ls" will give the same result here).

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now