简体   繁体   中英

sed with special characters

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
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.

Backslash works fine. echo '*.cpp' | sed 's/\\*//' 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/\\\\$//" echo '$.cpp' | sed "s/\\\\$//" or echo '$.cpp' | sed 's/\\$//' 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

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

I have one use case where I have to replace a text with a variable, that variable contains a special symbol, like (xyz-compute@developer.gserviceaccount.com). This @ symbol was creating an issue. So I found this solution useful.

SERVICE_ACCOUNT="xyz-compute@developer.gserviceaccount.com"
sed -i 's/DEVOPS_SERVICE_ACCOUNT/'${SERVICE_ACCOUNT}'/g' file.txt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM