Friday, September 4, 2009

Rename file to uppercase except extension - Bash


My present working directory got the following files.

$ ls -1
new.py
readme.txt
sl.pl
test.py

Required: Make all file in this directory uppercase but not their extension (ex: image.jpg becoming IMAGE.jpg)

The shell script on the command prompt:

$ ls | while read file
> do
> name=${file%%.*}
> extn=${file##*.}
> newfilename=$(echo $(echo $name | tr 'a-z' 'A-Z').$extn)
> echo "Moving $file to $newfilename"
> mv $file $newfilename
> done

Note: Linux secondary prompt (PS2)
The > (greater than sign) is the Linux secondary prompt (PS2).
When one issues command that is incomplete, the shell will display this prompt and will wait for the user to complete the command and hit Enter again.

Output of the above bash script:

Moving new.py to NEW.py
Moving readme.txt to README.txt
Moving sl.pl to SL.pl
Moving test.py to TEST.py

Now

$ ls -1
NEW.py
README.txt
SL.pl
TEST.py


Related post:
- Renaming file from lowercase to uppercase in Bash

2 comments:

Anand Subramanian said...

Thank you. I really enjoy your scripting articles.

Boris said...

Amazing ;)
Thanks.

© Jadu Saikia www.UNIXCL.com