Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i replace [] brackets using SED

I have a string that i am want to remove punctuation from.

I started with

sed 's/[[:punct:]]/ /g'

But i had problems on HP-UX not liking that all the time, and some times i would get a 0 and anything after a $ in my string would dissappear. So i decided to try to do it manually.

I have the following code which works on all my punctuation that I am interested in, except I cannot seem to add square brackets "[]" to my sed with anything else, otherwise it does not replace anything, and i dont get an error, so I am not sure what to fix.

Anyways this is what i currently have and would like to add [] to.

sed 's/[-=+|~!@#\$%^&*(){}:;'\'''\"''\`''\.''\/''\\']/ /g'

BTW I am using KSH on Solaris, Redhat & HP

like image 279
nitrobass24 Avatar asked Aug 30 '12 19:08

nitrobass24


People also ask

How do you remove square brackets using sed?

Try this: sed 's/[()]//g' <<< Hi(hello).

How do you replace special characters in sed?

You need to escape the special characters with a backslash \ in front of the special character. For your case, escape every special character with backslash \ .

How do you replace something with sed?

Find and replace text within a file using sed command The procedure to change the text in files under Linux/Unix using sed: Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input.txt. The s is the substitute command of sed for find and replace.

How do I remove a bracket in Linux?

We will use the tr command with the -d or –delete option in the Linux/Unix system to remove the braces symbol. This tr (translate) command is used to translate or delete characters from a file or standard input in the Linux system using a terminal.


1 Answers

You need to place the brackets early in the expression:

sed 's/[][=+...-]/ /g'

By placing the ']' as the first character immediately after the opening bracket, it is interpreted as a member of the character set rather than a closing bracket. Placing a '[' anywhere inside the brackets makes it a member of the set.

For this particular character set, you also need to deal with - specially, since you are not trying to build a range of characters between [ and =. So put the - at the end of the class.

like image 78
William Pursell Avatar answered Sep 18 '22 10:09

William Pursell