Parent path is /opt/data/ and within data folder there are multiple subfolders and within those subfolders there are multiple files which I want to rename only some part of it using bash.

Original file name:

WK6LZTPR99999999_dig_2017-07-10 01:55:57.xy

which I want to change all files with in all sub directory as:

WK6LZTPR99999999_cur_2017-07-10 01:55:57.mp3

Hope I elaborate the scenario clearly.

solution was given by philiphs work great but it is changing the other file extension as well in directories , I want to change only .xy file tension and other then that extension should be excluded.


You can loop through all files with a for loop, then remove the suffix using ${variable%suffix} syntax and finally replace that middle part with the ${variable/search/replace} syntax:

for file in /opt/data/*/*; do
  mv "$file"xy "${file/dig/cur}mp3"
| improve this answer | |
  • one check should be there , I've created a test.sh tst.img in a sub directories it does rename those file , it suppose to rename only .xy extension instead. – Shen Ben Aug 14 '17 at 8:58
  • That's what you asked for, right? Feel free to change the suffix. If you want it to work for all possible suffixes (what if two files have the identical name, but different suffix?), use filename="${file%.*}and mv "$file" "${filename/dig/cur}.mp3" – Philippos Aug 14 '17 at 9:03
  • thanks for your prompt response Ive made follwing changes to the script #!/bin/bash for file in /opt/data/*/*; do filename="${file%.xy}" mv "$file" "${filename/dig/cur}.mp3" done Now its adding suffix to file I.E test.sh.xy and file.img.xy , All I want script omit those all other file extension in subdirectories and only make changes to .xy extension files. – Shen Ben Aug 14 '17 at 9:16
  • WIth filename="${file%.mp3}" you are only removing the .mp3 extension. When you also want to remove a .sh or .img or whatever extension, use filename="${file%.*}" – Philippos Aug 14 '17 at 9:20
  • ok I got it , is there any way to exclude other file extension in directories and changes ile name end with .xy files extensions – Shen Ben Aug 14 '17 at 9:26

Not the answer you're looking for? Browse other questions tagged or ask your own question.