1

I have 5 filenames created inside a folder for one operation.The filenames are in the following format.

ES_currentdate_currenttime_processid_uniqueid.log

I want to read the status from the latest created file in that path.

The way I form the filename in shell script is:

$ filename=ES_*_uniqueid.log
$ echo grep "##status##XRB##" $HOME/log/$filename | sort -u` "

When I grep it reads the status from all 5 files and echoes it. I want the string to be grep only from the latest file that got created.

Could some one provide a solution?

2
  • Can you please show the actual names of a couple of the files? Need to see the timestamp format.
    – slm
    Aug 8, 2013 at 7:27
  • You was needed to put only one file to grep input and that file should be the last modified; slm did it :)
    – rook
    Aug 8, 2013 at 7:52

2 Answers 2

2

So long as the files were written in chronological order the names of the files doesn't really matter. Just use tail -1 to get the last file in a listing of the files and that should always be the latest file:

$ filename=ES_*_uniqueid.log
$ grep "##status##XRB##" $(ls -tr $filename | tail -1)

This will run the sub-command ls -tr $filename | tail -1 which will return a single result, the most recent file. This file will then be grepped for strings matching ##status##XRB##.

0

In zsh (explanations:

grep "##status##XRB##" ~/log/ES_*.log(om[1])

If the dates are in a sensible format (YYYYmmdd_HHMMSS), then the lexicographic order on the file names corresponds to the chronological order. So in ksh or bash, you can put the names of the matching files in an array: the file you're after will be the last array element.

logs=(~/log/ES_*.log)
grep "##status##XRB##" "${logs[${#logs}-1]}"

With only a POSIX shell (e.g. /bin/sh), you can use the positional parameters.

grep_last_match () {
  eval set -- \"\${$#}\"
  grep "##status##XRB##" "$1"
}
grep_last_match ~/logs/ES_*.log

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .