How to remove trailing characters in filenames in Bash?

In shell, one could do simply:

for x in *]*.avi ; do 
    mv -i "$x" "${x%]*.avi}.avi"
done

The shell can produce a list of the filenames with just a regular glob, and ${var%pattern} removes the (shortest) matching pattern from the end of the string in variable var. Since the final extension is always .avi, I just removed it with the pattern and added it back. With the quotes, this should work with file names containing spaces too, like Fancy Name for a Show.s01e01]Asdf.avi


This will rename the files. You need the \w* to signify any number of alphanumeric characters.

rename 's/\]\w*//' *

Reference: http://www.troubleshooters.com/codecorn/littperl/perlreg.htm#UsingSimpleWildcards


This is all kinds of impractical - the other answers are much faster and shorter - but...

You can use PowerShell! Microsoft open-sourced it recently and made it cross-platform. For downloads and installation instructions for your OS, see the "Get PowerShell" section.

Once you get it installed, you can use this brief script:

Get-ChildItem -File '*]*.avi' | ForEach-Object {
    Rename-Item $_ -NewName (($_.Name -Split ']')[0] + '.avi')
}

Basically, it goes through each object in the current directory that is a file matching *]*.avi, gets the part before the bracket, tacks .avi back onto it, and assigns that as the new name.

To run it directly from Bash, use this semi-golfed one-liner:

powershell -command $'gci -File \'*]*.avi\'|%{rename-item $_ -NewName (($_.Name -Split \']\')[0]+\'.avi\')}'

Quote escaping courtesy of this Stack Overflow answer.

(Tested in Bash on Ubuntu on Windows. There's probably a much shorter way of doing it with PowerShell, but I wanted to show something that's comprehensible to people who don't know regular expressions.)

Tags:

Linux

Bash

Rename