I'm trying to find a way to remove parenthesis and brackets from directories, but they don't have all the same pattern. Some are like this: (1234) ABC [xyz]. Others are like this [xyz] ABC (1234)(987).

Edit: The desired output would be ABC

How can I do this?

  • 1
    Add some examples and your desired output from those...
    – heemayl
    Mar 10 '17 at 5:53
  • Do you have duplicate directory names ? For example, (1234) ABC [xyz] and [xyz] ABC (1234) , if you remove items with brackets, both become ABC, so you basically might overwrite one with the other. Mar 10 '17 at 8:31

You can use rename to remove any of those characters wherever they occur with alternation

rename -n 's/\(|\[|\]|\)//g' *

You need to escape the brackets and parentheses.

Remove -n after testing to really do the renaming.

To remove all the characters within brackets or parentheses

rename -n 's/\(.*\)|\[.*\]//g' *

To also remove spaces (to change (1234) ABC [xyz] to ABC)

rename -n 's/\(.*\)|\[.*\]| //g' *
  • The output always have a ')' as the last character, is this because I'm not escaping the parentheses properly? Other than that it worked.
    – AvantGarde
    Mar 10 '17 at 6:31
  • show me your command @AvantGarde :)
    – Zanna
    Mar 10 '17 at 6:33
  • I tried using rename -n 's/\(|\[|\]|\)//g' *.
    – AvantGarde
    Mar 10 '17 at 6:43
  • I mistook the parenthesis after the output as being part of the output. So there was no problem with the code.
    – AvantGarde
    Mar 10 '17 at 6:49
  • oh I see! yeah that can be confusing @AvantGarde :)
    – Zanna
    Mar 10 '17 at 6:58

Not the answer you're looking for? Browse other questions tagged or ask your own question.