How to bulk changing partial file name in Linux?

I have a bunch of database files in a directory. Their name are like:

1234_ABCD_01.dbf, 28hrs_ABCD_02.dbf

I want to change them in bulk to:

1234_XXXU_01.dbf, 28hrs_XXXU_02.dbf.

I mean I just want to replace ABCD by XXXU. don't change other part of the file name and the contents of the file. What is the best and easy way to do it. Please help me to figure out the Linux command or script. Thanks in advance.

This is the most straight forward:

#!/usr/bin/ksh

ls *dbf | while read f
do
    echo mv $f ${f/_ABCD_/_XXXU_}
done

Probably works in bash. Execute it and verify that the move commands list the filie names correctly, then remove the echo to actually do the renaming.

The syntax ${var/string/repl} replaces the first occurrence of 'string' that it finds in the contents of var, with 'repl.'

agama:

Thanks a lot. It worked precisely. You are the guru.

Except that the solution would have problems taking care of files with white spaces..., if any. Its bad practice to use ls and pipe to while loop (extra overheads) to loop over files like that. Use shell expansion instead. eg

for file in *ABCD*...
do
  ....
done

Alternatively, if you have Ruby(1.9.1+), here's a one-liner

$ ruby -e 'Dir["*ABCD*"].each {|f|File.file?(f) &&File.rename(f, f.gsub("ABCD","XXXU"))}'

kurumi:

Thanks for your advice. This gave more ways to handle my case. I have learned from you.