How to rename files using script

Shell script

Extract from 3rd to 5th characters of the file name
#!/bin/sh
dir=Path of the working directory
cd $dir
for file in *.txt
do
    After=`echo $file | cut -c 3-5`
    mv "${file}" "${After}.txt"
done
#!/bin/sh
dir=Path of the working directory
cd $dir
for file in *.txt
do
    After="${file:2:3}"
    extension="${file##*.}"
    mv "${file}" "${After}.${extension}"
done

Add prefix "P-" and suffix "-S"
#!/bin/sh
Prefix=P-
Suffix=-S
dir=Path of the working directory
cd $dir
for file in *.txt
do
    filename="${file%.*}"
    extension="${file##*.}"
    mv "${file}" "${Prefix}${filename}${Suffix}.${extension}"
done

Batch file (For MS DOS)

Sometimes, we cannot use shell commands.
In such a case, Batch file for windows may be useful.

To execute following programs,
copy and paste code to "Notepad" and save with ".bat" extension.

Ex. : Delete first two characters. (abcde.txt→cde.txt)

Edit file name except for extension.

for %%F in (*.txt) do call :sub "%%F"
goto :EOF

:sub
  set BEFORE=%~1
  set FILENAME=%~n1
  set EXTENSION=%~x1
  set AFTER=%FILENAME:~3%%EXTENSION%
  ren "%BEFORE%" "%AFTER%"
goto :EOF
  • %~x1: Get Extension of the file
  • %~n1: Get filename without extension
  • ren A B: Rename filename from A to B

Ex. : Add "prefix" at the beginning of a file name. (abc.txt→prefixabc.txt)

To add character string "prefix" to the beginning of the filename,
write just like this.

for %%F in (*.txt) do ren "%%F" "prefix%%F"

Ex. : Add "suffix" at the end of the file name. (abc.txt→abcsuffix.txt)

Same idea as above, but be careful not to edit extension.
To do this, decompose filename before editing:

Filename + suffix + Extension

for %%F in (*.txt) do ren "%%F" "%%~nFsuffix%%~xF"