Change File Name by Shell

Update 2011 Dec. 14

replace jpg with JPG using ${i/jpg}JPG
for i in *.jpg; do
    j=${i/jpg}JPG
    echo "$i $j"
done

Description

When you want change file names in the Unix Shell, you can use # and % to match a part of the file name and replace this part with other strings you want.

Principle

old="human.fa"
new=chimp${old#human}
echo $old $new

the result is

human.fa chimp.fa
old="music.mp3"
new=${old%mp3}wav
echo $old $new

the result is

music.mp3 music.wav

with the help of *

You can also use the * to help # and % match variable things. Let's see some examples:

Change extension of a lot files

for i in *.wav; do 
    echo $i ${i%.*}.mp3; 
done

the result is:

a.wav a.mp3
b.wav b.mp3
c.wav c.mp3
for i in *.wav; do mv "$i" "${i%%.wav}.mp3"; done

Change the first underline to dot

for i in *_*; do echo $i ${i%%_*}.${i#*_}; done

result:

ha1_r1_fa ha1.r1_fa
ha1_r2_fa ha1.r2_fa
ha2_r1_fa ha2.r1_fa
ha2_r2_fa ha2.r2_fa

Change the last underline to dot

for i in *_*; do echo $i ${i%_*}.${i##*_}; done

result:

ha1_r1_fa ha1_r1.fa
ha1_r2_fa ha1_r2.fa
ha2_r1_fa ha2_r1.fa
ha2_r2_fa ha2_r2.fa

Change file name from upper to lower case

for i in *; do echo $i `echo $i | tr [:upper:] [:lower:]`; done
Homepage
Comments

Hide Comments