Adding a backslash in front of square brackets with sed

I'm trying to convert this line:

[some text]

to

\[some text\] 

with sed.

This is what I have so far:

sed -e 's/\[\([^]]*\)\]/\\\\\[\1\\\\\]/'

but this still gives me [some text].

Any suggestions?

Like this?

sed 's/[][]/\\&/g'

And please use code tags when posting code or sample input/output.

2 Likes

Try:

sed 's/[][]/\\&/g'
1 Like

Haha... I'd call that a tie :slight_smile:

Works great! Can one of you explain what is happening with the regular expression?

It means replace a character that is either a ] or a [ , ( [][] ) and replace that with a \ ( \\ ) followed by the character that got substituted in the first part ( & ). Repeat that for every such character ( g )

1 Like

The outer brackets mean "character class", same as if you do [0-9] or [a-z], the inner brackets are the characters to be matched (any of the two). Ampersand recalls the pattern that was matched (in this case only one char -- one of the brackets).

1 Like

A ] character within a [character_set] must be first, to not become the closing ]

1 Like

Thanks mirni!

And everyone else! It wasn't just me who provided relevant info :slight_smile:
You're welcome!

I tried

sed s'/[][]/\\&/g'

but it replaced the square brackets with &. Any suggestions?

Note: I'm writing this sed command to a file using perl - maybe I need to add more backslashes. Will try now.

Perl and sed are not the same thing. Although I am quite rusty in Perl, this should do the trick:

 perl -pe s'/([][])/\\$1/g'

What is your OS and version? How do you write this sed command to a file using perl? Did you use single quotes or double quotes?

I'm using Red Hat, 2.16.0. Here is the line of perl code I'm using to write the sed command to the shell script:

print {$sh} "set expr=`echo $temp | sed 's/[][]/\\&\g'`\n";

Are you trying to call the sed external command or are you trying to trying to write a literal string containing echo, pipe and the sed command itself to a dynamically created shells script? In the first case you would need to use 4 backslashes and the backslash before the g needs to be forward. In the latter case, perhaps you should use a here-doc.

print {$sh} "set expr=`echo $temp | sed 's/[][]/\\\\&/g'`\n";

Better do it in perl

$temp =~ s/([][])/\\$1/g;
print {$sh} "set expr=$temp\n";