0

How to rename multiple folder/files by user defined.

Say for Ex. I have multiple folders like krish, moorthy, ravi, robert, etc..

I want to rename all these directories as script_1 , script_2, script_3 etc

I tried below script but it doesnt produce a output

for i in * do mv $* $script_'$i' done

while executing it says it cannot move, cannot stat *

Please help me to go through this.

1

There are so many things wrong with your script, that it is difficult to know where to begin.

First, the syntax needs end-of-line markers:

for i in *; do mv $* $script_'$i'; done

Now the mv parameter 1 needs to be the name of the current file:

for i in *; do mv $i $script_'$i'; done

Next the mv parameter 2 has three errors ($script_ expands the non-existent variable script_; the quotes in '$i' make it a literal; and you need a second variable with a count in it to expand to the name you want), so you need something like:

n=1; for i in *; do mv $i script_$n; ((++n)); done

This will work, provided there are no blanks in the file names and provided there are no non-directory files in the current directory. So lastly we arrive at:

n=1; for i in *; do if [ -d "$i" ]; then mv "$i" script_$n; ((++n)); fi; done
0

perl-rename is well suited for this:

$ cd -- "$(mktemp --directory)"
$ mkdir foo bar baz
$ perl-rename --dry-run --verbose 's/.*/sprintf "script_%04d", ++$main::Mad/e' ./*/
./bar/ -> script_0001
./baz/ -> script_0002
./foo/ -> script_0003

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.