简体   繁体   中英

search and replace complex string in linux

I need some text search-replace with minimal tools during linux startup. Sed does not work, probably it finds some special characters in my strings. Is there a solution to turn off this fancy regexp magic and do simple literal search-replace of all plain text occurrences in file? One example which I cannot get to work:

sed -i 's|<![CDATA[http://example.com/file.json]]>|mysvc://{source}|g' my-file.xml

I have about 10 of other different text fragments, these can be long XML, jsons or other with all kind of special chars inside. It would be nice if the command would be maintainable (readable) also.

sed ONLY understands regexps, it does not understand strings. To try to force sed to treat regexps like strings is painful (see Is it possible to escape regex metacharacters reliably with sed ) and usually not worth bothering with when you can instead just use awk which DOES understand strings. eg:

awk '
BEGIN {
    old = "<![CDATA[http://example.com/file.json]]>"
    new = "mysvc://{source}"
}
s=index($0,old) { $0 = substr($0,1,s-1) new substr($0,s+length(old)) }
{ print }
' my-file.xml

The above is, obviously, untested since you didn't provide any testable sample input/output.

If you need "inplace" editing then if you have GNU awk use awk -i inplace ... and with other awks just use a tmp file: awk '...' my-file.xml > tmp && mv tmp my-file.xml .

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