how to change the extension of multiple files using bash script?

unique_programmer picture unique_programmer · Apr 5, 2013 · Viewed 14.6k times · Source

I am very new with linux usage maybe this is my first time so i hope some detailed help please. I have more than 500 files in multiple directories on my server (Linux) I want to change their extensions to .xml using bash script I used a lot of codes but none of them work some codes i used :

for file in *.txt
do
mv ${file} ${file/.txt}/.xml
done 

or

for file in *.*
do
mv ${file} ${file/.*}/.xml
done

i do not know even if the second one is valid code or not i tried to change the txt extension beacuse the prompt said no such file '.txt'

I hope some good help for that thank you

Answer

Édouard Lopez picture Édouard Lopez · Apr 5, 2013

Explanation

  1. For recursivity you need Bash >=4 and to enable ** (i.e. globstar) ;
  2. First, I use parameter expansion to remove the string .txt, which must be anchored at the end of the filename (%) :
  3. the # anchors the pattern (plain word or glob) to the beginning,
  4. and the % anchors it to the end.
  5. Then I append the new extension .xml
  6. Be extra cautious with filename, you should always quote parameters expansion.

Code

This should do it in Bash (note that I only echothe old/new filename, to actually rename the files, use mv instead of echo) :

shopt -s globstar # enable ** globstar/recursivity
for i in **/*.txt; do
    [[ -d "$i" ]] && continue; # skip directories
    echo "$i" "${i/%.txt}.xml";
done