Shell move file with renaming them

55 views Asked by At

I am using below line to copy html files from source dir to target dir. How can I rename the files while moving them to 001.html, 002.html, 003.html etc ?

find ${SourceDir} -type f -regex ".*\.\(htm\|html\|xhtm\|xhtml\)" -exec mv {} "${TargetDir}" \;
1

There are 1 answers

7
devnull On BEST ANSWER

You could use a counter in a loop and use shell parameter expansion to get the file extension.

The following might work for you:

i=0
while read -r file; do
   fn=$(printf "%03d" $((++i)))       # get incremental numbers: 001, 002, ...
   mv "${file}" "${TargetDir}/${fn}.${file##*.}";
done < <(find ${SourceDir} -type f -regex ".*\.\(htm\|html\|xhtm\|xhtml\)")

If your shell doesn't support process substitution, you might say:

i=0
for file in $(find ${SourceDir} -type f -regex ".*\.\(htm\|html\|xhtm\|xhtml\)"); do
   fn=$(printf "%03d" $((++i)))       # get incremental numbers: 001, 002, ...
   mv "${file}" "${TargetDir}/${fn}.${file##*.}";
done

Be warned that this might not work if the filenames contain weird characters.