Finding the file name in a directory with a pattern

I need to find the latest file -filename_YYYYMMDD in the directory DIR . the below is not working as the position is shifting each time because of the spaces between(occuring mostly at file size field as it differs every time.)

please suggest if there is other way.

report =�ls -ltr $DIR/filename_* 2>/dev/null | tail -1 | cut -d � � -f9�

There are lots of problems here:

  • there can't be a space before the <equals-sign> in an assignment statement,
  • you need to use ASCII <double-quote> characters to quote shell arguments; not a pair of Unicode <opening-double-quote> characters,
  • a command substitution needs to be surrounded by a pair of ASCI <back-quote> characters or (depending on what shell you're using) a $( at the start and a ) at the end; not by an ASCII <back-quote> at the start and an ASCII <apostrophe> at the end, and
  • there is no reason to use long format ls output when you just want the filename.

Maybe this will come closer to what you need:

report=`ls -t "$DIR"/filename_* 2>/dev/null | head -1`

In addition to what Don has listed, you may still hit problems if there are lots of files that match the filename pattern. This is because the shell will expand the pattern to match the list of all files before passing it to ls to list them in modification time order ( -t ), newest first. Because of this, you might overstep the limit of the command line. You haven't suggested how many files this might match. Is it a lot?

This is a system specific limit and you may never hit the maximum command line length, but if this is the case, you might be into a rather painful process to read the timestamp on each file and sort them yourself. Perhaps something like this might do the trick:-

for file in "${DIR}"/filename_*
do
   stat -c '%Y %n' "${file}"
done | sort -n | tail -1 | cut -f2- -d" "

It's messy, I know, but it might get round the command line limit, if you were to hit that.

As well as using CODE tags as in the tutorial, please can you also include details of the OS and shell you are using on each thread. The output from uname -a and ps -o cmd= -p $$ should suffice, unless your question is hardware/devices in nature.

I hope that you don't need the above code, but it might help.

Kind regards,
Robin