1753762 Members
4822 Online
108799 Solutions
New Discussion юеВ

Regex sed issue

 
SOLVED
Go to solution
Allanm
Super Advisor

Regex sed issue


Hi All,

The following doesn't work on the command line-

#root@admin ]ls /cbo*/conf/hosts.conf | egrep -v '/cbo[^/]*\\.' | sed -e's/.*\\(cbo[^/]*\\)\\/.*/\\1/'
sed: -e expression #1, char 25: Unknown option to `s'

while it works if I pass the command to a variable-

hostsem=`ls /cbo*/conf/hosts.conf | egrep -v '/cbo[^/]*\\.' | sed -e's/.*\\(cbo[^/]*\\)\\/.*/\\1/'`

Please help as to why is that the case. What I need to do to make it work on the command line.

If you can elaborate on the regex after the sed -s that would be great as well.

Thanks,
Allan

3 REPLIES 3
James R. Ferguson
Acclaimed Contributor
Solution

Re: Regex sed issue

Hi Allan:

Reduce the double escape ('\\') to a single excape ('\') and the command works on the command line.

If you use the preferred Posix syntax instead of backticks, you get the same syntax error you see on the command line. That is, this fails:

# hostsem=$(ls /cbo*/conf/hosts.conf | egrep -v '/cbo[^/]*\\.' | sed -e's/.*\\(cbo[^/]*\\)\\/.*/\\1/')

I am not sure why the use of backticks makes this "work".

As for the 'sed' regular expression it looks for the sequence "cbo/" and if found it substitutes "cbo" for the whole line's sequence, printing the substition. The parenthezied part is what is captured and the \1 is a back-reference to the captured part. The [^/] means _not_ the "/" character. A dot is any character. A "*" means zero or more occurances of the preceding character.

Regards!

...JRF...





Dennis Handly
Acclaimed Contributor

Re: Regex sed issue

I would also use a different delimiter than "/". It appears that you aren't quoting the "/" in the brackets but it appears you don't need to?
But this is clearer:
's:.*\(cbo[^/]*\)\/.*:\1:'`
Suraj K Sankari
Honored Contributor

Re: Regex sed issue