Ubuntu – How to remove square brackets, any text inside, and space after & before the brackets

bashbatch-renamecommand linesed

I have a lot of photos that need to be renamed.

[Wedding] Happy Day_001 [February].jpg
[Mountain] Summer Camp_165 [May].jpg
[Beach] Music Fest_58 [August].jpg

I need all the square brackets to be removed. To do so, I found this & this.

Using sed command as in those pages, the space before and after the brackets is still there. In my case, I want the text inside, space before & after, and the brackets itself to be removed.

Happy Day_001.jpg  
Summer Camp_165.jpg  
Music Fest_58.jpg

To remove [first]  &  [last] brackets, how can I do that with a sed command?

Best Answer

sed is the wrong tool. It doesn't rename files. While you can pair it with something that can, it's simpler to use rename from Perl:

rename -n 's/\[.*?\]//g' *

With -n, rename will show what changes will be made. Run without -n to actually rename the files. rename is Perl, and in Perl, .*? is not a greedy match like .*, so you don't need to use tricks like [^]]*.

To remove surrounding whitespace as well:

rename -n 's/\s*\[.*?\]\s*//g' *