I want to remove all special characters leaving only A-Za-z0-9.()[]

echo 'Some Movie Name! (2015) [1080p]' |sed -e 's/[^A-Za-z0-9.()[]]/./g'

Gives me this output:

Some Movie Name! (2015) [1080p]

This is what I want:


I cant figure out how to escape the "]" "]" doesn't work.

The closest I can get is this:

echo 'Some Movie Name! (2015) [1080p]' |sed -e 's/[^A-Za-z0-9.()[]/./g'

Then I can pipe it to sed again to remove double periods:

|sed 's/\.\././g'

2 Answers 2


Based on @Glenn Jackman's keen observations the method is changed to the following:

$ printf '%s' "$string" | tr -cs '[:alnum:].[]()'

°  -c => invert/complement the input set
°  -s => will squeeze consecutive characters from the complemented input set found in the data to a single dot character. 
  • You don't even need to include the \n -- assuming the OP will capture the output in a command substitution, any trailing newlines get removed anyway. Oct 18, 2019 at 20:56
  • Oh, I see that the trailing newline is replaced by a dot. In that case, change echo to printf "%s", or use a here-string: tr -cs '[:alnum:].[]()' . <<< 'Some Movie Name! (2015) [1080p]' Oct 18, 2019 at 20:57
  • and I would suggest, for better readability, keep the bracket pairs together: tr -cs '[:alnum:].[]()' . Oct 18, 2019 at 21:00

Put the closing ] you want to match directly after the negation ^ where it is not misinterpreted. You can use \+ at the end of the regex to replace multiple characters with one period (thanks @Rakesh Sharma):

$ echo 'Some Movie Name! (2015) [1080p]' | sed -e 's/[^][A-Za-z0-9()]\+/./g'
  • Also now remove the dot from the list. Oct 18, 2019 at 2:08
  • Ah, right, good catch!
    – Freddy
    Oct 18, 2019 at 2:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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