Ubuntu – How to remove characters from file names using command line

batch-renamecommand linerename

I have a bunch of files needing renaming but I do not want to create a script for it, just a command line.

I need to remove the last digits between the . and the .gif:

22771786_01.204.gif  
22771786_02.203.gif  
22771786_03.10.gif  
22771786_04.56.gif

To be like this:

22771786_01.gif  
22771786_02.gif  
22771786_03.gif  
22771786_04.gif

Best Answer

You can achieve this with a for loop and some bash expansion. If you're already in the directory containing the files:

for f in ./*; do mv "$f" "${f%.*.gif}.gif" ; done

If your directory containing the files is called /home/gifstore/ :

for f in /home/gifstore/*; do mv "$f" "${f%.*.gif}.gif" ; done

The ${f...} performs expansion of each filename we've saved into the variable named f. The % in the expansion of the filename means remove the shortest match of the following pattern from the end of the variable. The pattern is .*.gif, meaning any amount of characters between . and .gif. Finally we append the literal string .gif outside of the expansion to create our new filename, and rely on the mv command to move the file.

This won't work for hidden files, starting with ..

Related Question