Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question
    
Can you please show the actual names of a couple of the files? Need to see the timestamp format. –  slm Aug 8 '13 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 '13 at 7:52
add comment

2 Answers 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##.

share|improve this answer
add comment

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
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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