Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

script to find latest file version

Status
Not open for further replies.

olmos

Technical User
Oct 25, 2000
135
US
I have a group of files some beginning with the similar name and date it was created at the end of the filename. For example, john_smith_2005-04-16
john_smith_2005-04-10
joe_harris_2005-04-01
joe_harris_2005-04-03

I need a way to get the latest version of a group of files, for
example I need to get only john_smith_2005-04-16 and joe_harris_2005-04-03 since these are the latest within their group.

How can I do this in a shell script ?

Thank you for any suggestions.
olmos
 
Hi:

This is one way:
Given that all the filenames are in datafile. Sort the file in reverse order so that the newest files for a given user are on top. Read the file a line at a time setting the field separator, IFS, to "_", and print out the line when fields 1 and fields 2 change:

#!/bin/ksh


f1_buf="start"
f2_buf="start"
sort -r datafile |
while IFS="_" read f1 f2 f3
do
if [[ "$f1" != "$f1_buf" && "$f2" != "f2_buf" ]]
then
echo "$f1"_"$f2"_"$f3"
f1_buf="$f1"
f2_buf="$f2"
fi
done
 
Thanks. This works. How can I get the whole output to
be put into a file ?
I tried adding echo "$f1"_"$f2"_"$f3" > outputfile
but it only puts the last line in a file.

olmos
 
Hi:

You're right. This command gives you only the last line:

echo "$f1"_"$f2"_"$f3" > outputfile

And that because you're redirecting each instance to the file overwriting the file each time. You need to append this way:

echo "$f1"_"$f2"_"$f3" >> outputfile

 
Thanks for your help. I have a problem though, when I checked the
outputfile it seems that if I have someone with the same
first name it will only get the latest revision for those with
the same first name . For example, john_smith_2005-04-10
and I have another john like john_jackson_2005-04-15, john_jackson_2005-04-16 it
will forget about john_smith_2005-04-10 and just give me
the latest for the group with the first name john.

Is there something that needs to be changed in the above
script to give me the correct output which would look at the
first and last name and give me the latest date ?

Thanks,
olmos
 
Replace this:
if [[ "$f1" != "$f1_buf" && "$f2" != "f2_buf" ]]
By this:
if [[ "$f1" != "$f1_buf" || "$f2" != "f2_buf" ]]

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ222-2244
 
Thank you very much for your help. it was also missing the $ sign on f2_buf

olmos.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top