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

Solution 1:

You shouldn't use sed to rename files, but you can use the Perl program rename, for example:

$ rename -n 's/\[[^]]+\] ([^[]+) \[[^]]+\]/$1/' *
rename([Beach] Music Fest_58 [August].jpg, Music Fest_58.jpg)
rename([Mountain] Summer Camp_165 [May].jpg, Summer Camp_165.jpg)
rename([Wedding] Happy Day_001 [February].jpg, Happy Day_001.jpg)

Remove -n after testing to actually rename the files.

Notes

  • s/old/new replace old with new
  • \[ literal [
  • [^[]+ some characters that are not [
  • (stuff) save stuff for later to reference as $1, $2 etc

This only works if your filenames are consistent. muru's answer is much more portable.

Solution 2:

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' *