开发者

Unable to find a sed pattern that works

开发者 https://www.devze.com 2023-02-24 04:39 出处:网络
I\'m trying to perform a string replacement on several hundred awstats config files, and using sed to do so. However, I\'m having trouble getting a working pattern.

I'm trying to perform a string replacement on several hundred awstats config files, and using sed to do so. However, I'm having trouble getting a working pattern.

To be specific, I'm trying to convert this line in the configs:

HostAliases="REGEX[^\.*example\.com$]"

into this:

HostAliases="REGEX[\.example\.com$]"

where example\.com is variant.

I've tried dozens of variations of sed command. For example:

sed -i 's/^HostAliases="REGEX[^\.*/HostAliases="REGEX[\./' /etc/awstats/*.conf

sed -i 's/REGEX[^\.*/REGEX[\./' /etc/awstats/*.conf

but each time get an error like: sed: -e expression #1, char 49: unterminated 's' command

开发者_如何转开发The issue is probably to do with escaping some of the characters but I can't figure out which ones or how to escape them. I want to make the pattern specific enough to avoid accidentally matching other lines in the config, so including the HostAliases would be good.

Could some sed guru please point me in the right direction?


The first argument to 's' is itself a regular expression. So you have to escape (with \) the special characters. In your case they are [, \, . and *. So it should be:

sed -i 's/^HostAliases="REGEX\[^\\\.*/HostAliases="REGEX[\./' /etc/awstats/*.conf
sed -i 's/REGEX\[^\\\.\*/REGEX[\./' /etc/awstats/*.conf


Is this what you mean?

$ echo 'HostAliases="REGEX[^\.*example\.com$]"' | sed 's/^HostAliases=\"REGEX\[\^\\\.\*/HostAliases="REGEX[\\\./'

Outputs:

HostAliases="REGEX[\.example\.com$]"


You need to escape special regular expression characters too, like this:

sed -i 's/REGEX\[\^\\.\*/REGEX[\\./' /etc/awstats/*.conf


You forgot to escape some chars, like ^ and [ . Your sed would be something like this:

sed -e 's/REGEX\[\^\.*/REGEX\[/' -i /etc/awstats/*conf
0

精彩评论

暂无评论...
验证码 换一张
取 消