Reputation: 783
Is there a way to extract the last modified date and time from a log file and attach that date and time to the file?
I have a tool that generates appslist.log file every time it is run. Through my script when I run the tool, the applist.log file is already there and then I may have to associate it with the time and date it was created.
Like:
mv applist.log applist_+%Y%m%d_%H%M%S.log
Like let's say I ran the tool the first time and it generated applist.log:
applist.log Mon 03-29-2013
The next time I run the tool on 03-30-2013, I want to move the existing applist.log file with a new name containing the date and time it was created:
like applist_03-29-2013.log
because the tool would again generate applist.log on 03-30-2013.
Upvotes: 1
Views: 9415
Reputation: 46
Getting the creation time of a file depends on the file system you're using.
Not all file systems support retrieving file creation time. Try:
stat --format=%w applist.log
If you get a single '-', your file system does not report the creation time. Otherwise, it prints the time.
If you get the creation time this way, you may use the following to do the move:
fileName="applist.log"
creationTimeEpoch="$(stat --format=%W "${fileName}")"
creationTime="$(date +%Y%m%d_%H%M%S --date="@${creationTimeEpoch}")"
mv -i "${fileName}" "${fileName%.log}_${creationTime}.log"
If not, you may use the modification time of the file:
fileName="applist.log"
modificationTime="$(date +%Y%m%d_%H%M%S --reference="${fileName}")"
mv -i "${fileName}" "${fileName%.log}_${modificationTime}.log"
Upvotes: 1
Reputation: 25069
mv applist.log applist_`date -r applist.log +%Y%m%d%H%M%S`.log
This will move the file to a new file with a date in the name. The date command allows you to display in any format. See man date
for a full description of these character sequences. Using back ticks will run the command inside first. The -r
option on date will get the date of the file in question.
Example:
[me@host temp]$ mv applist.log applist_`date -r applist.log +%Y%m%d%H%M%S`.log
[me@host temp]$ ls -l
total 196
-rw-rw-r--. 1 me me 0 Mar 25 20:55 applist_20130325205532.log
I assume your program is a cron and will not run more than once a second.
Upvotes: 1