Operating System - HP-UX
1829265 Members
9606 Online
109988 Solutions
New Discussion

changing date in filename with shell script

 
SOLVED
Go to solution
Andy Koumi_1
Occasional Contributor

changing date in filename with shell script

Hi,

I've been tasked with creating a unix shell script that will update the date in the filename string to the current date & time. i.e. the file is currently named PP7K_20040426120002.drf and I would like to change it twice a day at mid-night and mid-day. Therefore at today midnight the filename would be changed to PP7K_20040427000000.drf and at mid-day today the filename would be changed to PP7K_20040427120000.drf etc, etc.

I'm a beginner at shell scripting and would be greatly appreciate any help that can be provided.

Cheers

AK
3 REPLIES 3
Scott Palmer_1
Trusted Contributor
Solution

Re: changing date in filename with shell script

#! /bin/sh

#assume only 1 in the directory
var=`ls -1 PK7K_*.drf`

mv $var PP7K_`date+%Y%m%d%H%M%S`.drf




this is about as simple as it gets.
if you just need to create a new file, and leave the old one, it is much simpler

#! /bin/sh
touch PP7K_`date+%Y%m%d%H%M%S`.drf


this is much simpler.

Regards
Scott Palmer
RAC_1
Honored Contributor

Re: changing date in filename with shell script

File=PP7K_20040426120002.drf

Cron entry that will run at mid-night and mid-day

mv ${File} PP7K_`date +%Y%m%d%H%M%S`.drf

Anil
There is no substitute to HARDWORK
rmueller58
Valued Contributor

Re: changing date in filename with shell script

I have a process I use to mv log files and date then in a similar fashion..

for example:

each day an file "export.log" is built in my log directory. I want to retain a weeks worth of export.log as export.log is overwritten nightly, I only want to capture it after the process has ran each day
in crontab my job looks like this

30 23 * * * /scripts/logrename

the script is simple,
#LOGRENAME script
mv /logfiles/export.log /logfiles/backup/export`date +%y%m%d_%H%M%S`.log


If I wanted two copys I add a second entry in the crontab;
30 12 * * * /scripts/logrename
30 23 * * * /scripts/logrename

this holds as log as the name of the original file is a constant, if the file name is a variable, then you'd have to parse your original file name with the ls command, and search for the intended string, and use it as a variable, in parameter $1 of the mv command..