Help with sed script?

David J Berube djberube at berubeconsulting.com
Tue Sep 5 16:36:00 EDT 2006


Hi all,

In short, the basic problem is that [^#] matches a space. Rewrite your 
character class so that it doesn't, and you should be all set.

For a slightly longer answer, let's briefly dissect this part of the regex:

^[[:space:]]*[^#].*[[:space:]]+xyz

It's looking for zero or more spaces, followed by a single character 
that's not #, followed by zero or more of any character, followed by one 
or more spaces, followed by the string literal xyz.

Take the following line:

    # Lorem ipsum dolor sit amet xyz

This should match, since the first [[:space:]]* can match two spaces, 
the [^#] can match the final space, and then the rest of the regex 
should match as well. You should always be extremely cautious with 
negative character classes and .*. It is necessary to look at regexes 
from two angles: what should this match, and what shouldn't this match?

Take it easy,

David Berube
Berube Consulting
djberube at berubeconsulting.com
(603)-485-9622
http://www.berubeconsulting.com/

Michael ODonnell wrote:
> I'm trying to use sed to rewrite lines in a config file that
> have a target string 'xyz' in them surrounded by whitespace
> and which are NOT commented out with a hash sign and which
> may or may not have leading whitespace.  This expression:
> 
>    sed -r -e '/^[[:space:]]*[^#].*[[:space:]]+xyz[[:space:]]*/{s/^.*$/REWRITTEN/}'
> 
> ...mostly works:
> 
>    echo 'abc xyz'  | sed -r -e '/^[[:space:]]*[^#].*[[:space:]]+xyz[[:space:]]*/{s/^.*$/REWRITTEN/}'
>    REWRITTEN
> 
>    echo ' abc xyz' | sed -r -e '/^[[:space:]]*[^#].*[[:space:]]+xyz[[:space:]]*/{s/^.*$/REWRITTEN/}'
>    REWRITTEN
> 
>    echo '#abc xyz' | sed -r -e '/^[[:space:]]*[^#].*[[:space:]]+xyz[[:space:]]*/{s/^.*$/REWRITTEN/}'
>    #abc xyz
> 
> ...but the part that's gonna make me go postal is that it seems
> like *any* leading whitespace makes the entire expression match
> even when it really shouldn't:
> 
>    echo ' #abc xyz' | sed -r -e '/^[[:space:]]*[^#].*[[:space:]]+xyz[[:space:]]*/{s/^.*$/REWRITTEN/}'
>    REWRITTEN
> 
> I'm probably missing something obvious but at this point I
> could sure use a few whacks with a clue-stick...
>  
> _______________________________________________
> gnhlug-discuss mailing list
> gnhlug-discuss at mail.gnhlug.org
> http://mail.gnhlug.org/mailman/listinfo/gnhlug-discuss
> 
> 



More information about the gnhlug-discuss mailing list