sed with special characters

Tag: linux , bash , unix , sed Author: lxy8838 Date: 2011-04-26

I have this line that I want to use sed on:

--> ASD = $start ( *.cpp ) <--

where $start is not a varaiable, I want to use sed on it and replace all this line with:

ASD = $dsadad ( .cpp ) 

How can I make sed ignore special charactars, I tried adding back slash before special characters, but maybe I got it wrong, can some one show me an example?

here is what i want :

sed 's/CPPS = \$(shell ls | grep *.cpp )/somereplace/' Makefile

Best Answer

sed 's/\$start/\$dsadad/g' your_file
>> ASD = $dsadad ( *.cpp ) 

sed 's/\*//g' your_file
>> ASD = $start ( .cpp ) 

To follow your edit :

sed -i 's/ASD = \$start ( \*.cpp )/ASD = \$dsadad ( .cpp )/' somefile
>> ASD = $dsadad ( .cpp )

Add the -i (--inplace) to edit the input file.


it is correct , but i need to add -i or else it will paste the file and will not replace, do you know why is that?
thanks, I edited my answer ;)

Other Answer1

Backslash works fine. echo '*.cpp' | sed 's/\*//' => .cpp

If you're in a shell, you might need to double escape $, since it's a special character both for the shell (variable expansion) and for sed (end of line)

echo '$.cpp' | sed "s/\\$//" or echo '$.cpp' | sed 's/\$//' => '.cpp'

Do not escape ( or ); that will actually make them them special (groups) in sed. Some other common characters include [ ] \ . ?

This is how to escape your example:

sed 's/ASD = \$start ( \*\.cpp )/ASD = $dsadad ( .cpp )/' somefile


but i have $ also and ( and ) , are they also special characters ?
i re edited my post, look at the last line
sed 's/ASD = \$start ( *\.cpp )/ASD = $dsadad ( .cpp )/' somefile not working
this echo -n 'ASD = $start ( *.cpp )' | sed 's/\(.*\)start\(.*\)\*\(.*\)/\1dsadad\2\3/' works for me
@shd You forgot the backslash at the first *.

Other Answer2

The chacters $,*,. are special for regular expressions, so they need to be escaped to be taken literally.

sed 's/ASD = \$start ( \*\.cpp )/ASD = $dsadad ( .cpp )/' somefile