Renaming files in Linux terminal in batch

Few days ago I have encountered a problem whereby I had to rename 10,000 files and remove a prefix (_BK). There are two approaches to handle such a problem,

  1. Rename files manually from GUI.
  2. Using a small bash script to do the job.

Here, I talk about second approach as first one doesn’t need an especial explanation.
Linux does not have any command for mass files renaming. Therefore, you are required to do bash scripting alongside mv command.

Let’s think how to do it in an algorithmic way. I write down following steps,

  1. For each file in the current or given directory read file names one by one.
  2. If the file name matches with the pattern (_BK).
  3. Rename the file (remove _BK from the file name).
  4. Go to the next file.

The algorithm is fairly simple and should be understandable even for non programmers.
Now, let’s move to the bash script based on the given algorithm.

for name in _BK*
newname="$(echo "$name" | cut -c4-)" #remove _BK from the file name
mv "$name" "$newname"

Leave a Reply