Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
Looking for some help in renaming files using a shell script.
Suppose I have a directory which contains several files, some of which are *.dat files. If there are 7 *.dat files, I would like to rename all 7 *.dat files to *.01, *.02, ... *.07
Here is what I have thus far:
ls -l *.dat $*| awk `
NF == 9 && /^-/{ #can someone explain this? this seems to loop through $
++filenum #increments to count number of *.dat files
print filenum, "\t", $9 #prints filenumber and current *.dat filename
newfile= $9 ".0" filenum #produces *.dat.01, but want *.01, *.02, etc
mv $9 $newfile # seems to do nothing, why?
}`Any help is greatly appreciated!

I'm having a problem following your awk code. One thing is sure: you can NOT embed other shell commands like mv inside an awk script - not without using the awk system command.
How about this script:
#!/bin/ksh
typeset -2Z i
i=0
ch /path/to/mydir
find . -type f -name "*.dat" -print|while read fname
do
((i=i+1))
echo "$i"
echo "$fname"
mv "$fname" "$fname.$i"
doneThe above scrpt might have problems if your directory has subdirectories with files named *.dat or if any of your file names contain a space.

Thank you -
With a little tweaking, I think what you provided will work. I added some code to replace the .dat with .01, etc. rather than append.
My only issue now is that I can't figure out what order it is applying these numbers in. When I sort by filename, the numbers are coming out *.04, *.01, *.03, *.01 - I would have thought it would take my input files in order of filename.
Also what is "ch" - this is not found by my system, and might have something to do with the ordering?
Thanks nails.

First, I'm a bozo. That "ch" is suppose to be a "cd" for change directory. I apologize.
Second, I don't know what to tell you about the sort issue without seeing the data and how you are using the sort command.
Oh, and you're welcome.

Well, I am not really using a "sort" command. It is picking the order in which to rename the files - and it doesn't appear to be based on filename, or file size.
Ideally, I'd like it to sort by filename prior to renaming.
Other than that, everything is working great.

![]() |
multiple grep
|
URGENT-check data within ...
|

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