Unable to find a sed pattern that works

342 Views Asked by At

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?

4

There are 4 best solutions below

1
On BEST ANSWER

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
1
On

Is this what you mean?

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

Outputs:

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

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

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

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

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