add character to the middle of a file name

bash, command-line

Solution

You can write:

for file in * ; do
    mv ./"$file" "${file:0:4}0${file:4}"
done

(See the explanation of `${parameter:offset}` and `${parameter:offset:length}` in §3.5.3 "Shell Parameter Expansion" of the Bash Reference Manual.)

Edited to add: If you only want to capture a specific subset of files, you can change `*` to a more-specific pattern such as `[0-9][0-9][0-9][0-9][0-9]` (which matches filenames consisting of five digits).

Incidentally, you can format the whole thing on one line:

for file in [0-9][0-9][0-9][0-9][0-9] ; do mv "$file" "${file:0:4}0${file:4}" ; done

Problem

I need to add a character to the middle of a file name, I need to do this for about 8000 files all in the same directory. I'm looking for a command-line option: Example (all files that need renaming are five digits, they are in a directory that contains other six-digit filenames that do not need to be renamed): ``` 01011 02022 12193 ``` To: ``` 010101 020202 121903 ``` I've tried a couple of things: rename, mv, etc. Similar to this (Bash - Adding 0's in the middle of a file name) but not exactly

Original source