Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
HI Gurus,
I have more than one file in a directory with different dates like file1-2212008.txt,file2-2222008.txt,file3-3012008.txt .what I need to do is I have to move most recent file (file3-3012008.txt )to one directoy and all others to another directory.Can you please tell me how to writ unix script
Thanks
Kanaka

I'm making a big assumption: namely, that the unix timestamps on the files follow your file naming convention. If they do, use the -t switch of the ls command. If they don't, you'll have to rip the date from the file name, and that's more work than I care to do:
#!/bin/kshcd /to/my/directory
i=0
ls -1t|while read ff
do
((i=i+1))
if [[ $i -eq 1 ]]
then
cp "$ff" /my/one/directory
else
cp "$ff" /my/other/directory
fi
done
Change the directory listing to suit your environment, and don't change cp to mv until you are sure the script is correct.

Thanks Nails for your reply.
Mean while I can use the logic that you send to move files
Unfortunately some times unix timestamp and the date on file doesn't match.Clients may send 2 files (today's and yesterday's ) on same day If their yesterday's file is not ready.Can you please give me some idea (like Pseudocode) I will try that
Thanks
Kanaka

Here's what I would do:
1) Strip out the date from the the file name. Given that the file always starts with the structure you gave, this sed command should do it:
fname="file1-3012008.txt"
# strip off the beginning file.. and the ending .txt:
echo "$fname"|sed -e 's/^file[0-9]*-//' -e 's/\.txt$//'2) You can NOT sort the date in the format 3012008. Use the cut command to get the Year, month and day, i.e. 2008301:
datestr="3012008"
# get the length of the datestr using ksh pattern
dlen=${#datestr}# get the year
yr=$(echo $datestr|cut -c $((dlen-3))-$dlen)
# get the month/day
md=$(echo $datestr|cut -c 1-$((dlen-3)) )# create the newdate string
newdatestr="${yr}${md}"
echo $newdatestr3) Now, if you cycle thru the directory as I showed you, for each file, strip out the date as in step 1).
4) Create a newdatestring as in step 2).
5) Build a string with the filename and the newdatestring:
# make sure a space exists between the strings:
string="$ff $newdatestring"and echo it to a newfile:
echo $string >> /tmp/newfile
6) Now, sort /tmp/newfile on the second field which is the newstring sending the output to a different file.
7) different file should now have your files in the correct order. Cycle thru different file and perform your move.
I've done the hard part stripping out the date and reformatting it. I'll leave putting to together to you.

![]() |
only want the interger
|
date command
|

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |