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?


2 Answers 2


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.


  • 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.

  • It works! Thank you. It has many brackets that I don't understand. Maybe can you give me a reference about it to read?
    – Hidayats
    Oct 23, 2017 at 10:34
  • Some of the brackets are literal and some are used for character classes (here just for negation with ^). I explained a little in my notes. Here's a small summary of Perl regex which links to a bigger one. But the regex I use here is the same for sed and grep so the regex sections in info sed, for example, may help @SandiHidayat
    – Zanna
    Oct 23, 2017 at 10:47
  • Good ol' rename, love it Oct 24, 2017 at 3:22

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' *
  • Ah, you're right. That's why I got an error. It's trying to edit the file itself rather than changing its name. I never used sed or rename before since mv is enough for me.Your answer is what i was looking for. It works perfectly! Thank you very much.
    – Hidayats
    Oct 23, 2017 at 10:22

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .