1

How do I open the latest file from list of files in a particular directory? Same file name arrange in date wise with latest in last.

Currently I am using following commands:

ls -lrt filename*
tail -f filename
2

If your shell is a Bourne-like shell and its [ builtin implements the -nt test to test whether one file is newer than another, you may use

newest=
for file in ./* ./.*; do
    if [ -f "$file" ]; then
        if [ -z "$newest" ] || [ "$file" -nt "$newest" ]; then
            newest=$file
        fi
    fi
done

if [ -f "$newest" ]; then
    printf 'The latest file is "%s"\n' "$newest"
else
    echo 'Could not find files here' >&2
    exit 1
fi

This would iterate over all regular (and symlink to regular) files (including hidden ones) in the current directory and then tell you which one was found to be the newest file. You would replace the printf statement with the actual command that you'd want to run on "$newest".

As a shell function, which additionally takes a list of files as its argument:

newest () (
    newest=
    for file do
        if [ -f "$file" ]; then
            if [ -z "$newest" ] || [ "$file" -nt "$newest" ]; then
                newest=$file
            fi
        fi
    done

    if [ -f "$newest" ]; then
        printf '%s\n' "$newest"
    else
        echo 'No files found' >&2
        return 1
    fi
)

Then

tail -f "$(newest ./filename*)"
0

You can use GNU find, to print all files with their last modified time, sort them in reverse order, get the latest modified file ( head -n 1 - top entry ) and then do a tail of the last modified file

  find <Directory-name> -type f -printf '%TY-%Tm-%Td %TT %p\n' | sort -r | head -n 1 | awk  '{print $3}' | xargs tail -f
0

If zsh is installed, you can do in it:

tail -f filenameCtrl+xm

Ctrl+xm is a completer that expands to the latest file (according to last modification time).

In a script:

#! /usr/bin/env zsh
tail -f filename*(om[1])

Where om sorts by modification time (most recent first) and [1] selects the first.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.