sakhunzai
sakhunzai

Reputation: 14500

Find the latest build file in directory

I need to get the latest build file in current directory . The logic is sth like this:

  1. Search for pattern in given build directory
  2. find the latest one among matched
  3. return basename for latest file name

I got this one so far but its not complete

   find  ./build  -iregex '.*/build_.*\.tar\.gz' -type f -exec basename {} \; 

I am puzzled around sorting it to get latest one

Upvotes: 1

Views: 78

Answers (3)

anubhava
anubhava

Reputation: 786271

This find should work using stat and sort:

find ./build  -iregex '.*/build_.*\.tar\.gz' -type f -exec stat -c '%Y %n' {} + |
    sort -rn -k1,1 | head -1 | cut -d " " -f2-

On OSX try this sed:

find ./build  -iregex '.*/build_.*\.tar\.gz' -type f -exec stat -f '%m %N' {} + |
    sort -rn -k1,1 | head -1 | cut -d " " -f2-

Upvotes: 1

hek2mgl
hek2mgl

Reputation: 158250

Having GNU find, you can use the following command:

find ./build  -iregex '.*/build_.*\.tar\.gz' -printf '%T@ %f\n' | sort -n | tail -n1 | cut -d' ' -f2

It uses find's printf action to print the timestamps of the latest modification along with the filename (basename). Then it pipes it to sort, extracts the last line using tail and finally separates the name from the timestamp using cut.

Upvotes: 0

gniourf_gniourf
gniourf_gniourf

Reputation: 46903

For a pure Bash possibility:

#!/bin/bash

shopt -s globstar nullglob nocaseglob

latest=
for file in ./build/**/build_*.tar.gz; do
    [[ -f $file ]] || continue
    [[ $latest ]] || latest=$file
    [[ $file -nt $latest ]] && latest=$file
done

if [[ $latest ]]; then
    echo "Latest build: ${latest##*/}"
else
    echo "No builds found"
fi

Upvotes: 1

Related Questions