Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid preceding regular expression given by sed

I am and have been working on a sed script file and I am running into an "Invalid Preceding regular expression" error when I run it. Below is the file in its entirety.

I have done much search on this already, both on this site and else where. Many questions asked here have resulted in needing to be either extend regular expressions something being escaped incorrectly. I have defined this as a extended expresion already as it is needed for the email substitution.

#!/bin/sed -rf
#/find_this thing/{
#s/ search_for_this/ replace_with_this/
#s/ search_for_this_other_thing/ replace_with_this_other_thing/
#}

#Search and replace #ServerAdmin (with preceding no space) email addresses using a regular expression that has the .com .net and so on domain endings as option so it will find root@localhost and replace it in line with admin's email address.

ServerAdmin/ { 
s/\b[A-Za-z0-9._%-]+@(?:[a-zA-Z0-9-]+\.)+(\.[A-Za-z]]{2,4})?\b/[email protected]/
}
#Enable user's Public HTML directories
/UserDir/ {
s/disable$/enable/ 
s/^#User/User/
}
#Replace the only #ServerName (with preceding no space) followed space and text with Our server ip
/#ServerName */ c\ ServerName server.ip.address.here/

I am calling it from termal as ./config-apache.sed /etc/httpd/conf/httpd.conf and get this returned.

/bin/sed: file ./apache-install.sed line 12: Invalid preceding regular expression

inside of vim line 12 is i dentified as the single } above #Enable user's Public HTML directories

like image 255
Spartan-196 Avatar asked Feb 18 '13 04:02

Spartan-196


People also ask

Does sed support regular expression?

Regular expressions are used by several different Unix commands, including ed, sed, awk, grep, and to a more limited extent, vi.

What regex does sed use?

4.3 selecting lines by text matching GNU sed supports the following regular expression addresses. The default regular expression is Basic Regular Expression (BRE). If -E or -r options are used, The regular expression should be in Extended Regular Expression (ERE) syntax. See BRE vs ERE.


1 Answers

It appears the GNU sed does not like the PCRE non-capturing notation:

...(?:...)...

Try:

s/\b[A-Za-z0-9._%-]+@([a-zA-Z0-9-]+\.)+(\.[A-Za-z]]{2,4})?\b/[email protected]/

GNU sed seems to be OK with that. However, you still have a little work to do. Given the first line below as input, the output is the second line:

abc [email protected] aaa
abc [email protected] aaa

There are two problems giving that result:

  1. The ]] should be a single ].
  2. You're looking for a trailing dot in the prior regex, so you don't want one in the last part of the domain suffix.

This does the job:

s/\b[A-Za-z0-9._%-]+@([a-zA-Z0-9-]+\.)+([A-Za-z]{2,4})?\b/[email protected]/

abc [email protected] aaa
abc [email protected] aaa
like image 117
Jonathan Leffler Avatar answered Sep 17 '22 15:09

Jonathan Leffler