The design of the script depends a little on if you want it to rename all file always that exist in the folder or if you want it to keep a specific order. I mean, do you want it to rename all files in case you add one more file to the folder, or that once they are renamed, they are never renamed again.
In theory all you need to do is have the file names and iterator and a text suffix, then you concatenate them. With ls you can get a list of the files in the directory, you can iterate over the lines of the output of ls to get the original names and an iterator number at the same step, then concat to that your suffix.
This would be possible to do with perl with the following steps
Code: Select all
$name = 'foo';
$filename = "/tmp/${name}.tmp";
I personally like to use perl for string substitutions and concatenations
but I believe you specifically want to use bash,
so how about this:
Code: Select all
bash-4.4$ touch a.txt
bash-4.4$ touch b.txt
bash-4.4$ touch c.txt
bash-4.4$ ls
a.txt b.txt c.txt
created a list of files with .txt suffix for testing
Code: Select all
bash-4.4$ ((count=0)); for item in *; do mv "$item" "Letter_Serial_${count}_${item%.txt}.odt"; ((count++));done
bash-4.4$ ls
Letter_Serial_0_a.odt Letter_Serial_1_b.odt Letter_Serial_2_c.odt
There are probably more eloquent ways to do this. In Python and many other scripting languages you can iterate a list of items pulling the names and a order numer (more precisely, the iteration step) at the same time thus not requiring the creation of a math variable. I don't know how to do that in bash. Does anyone else?
Also, if you use this in the same directory again it will attempt to rename *. But if you know that the files will always end in .txt you could loop over *.txt instead, and the in the future the script would not ever attempt to rename already once processed files.
Also, the use of mv here renames the file without retaining the original, but using cp instead of course would retain the original
Also realize that if you remove b.txt and rerun the script, c.txt will get a different serial number.