Help with sed script?

Mark E. Mallett mem at mv.mv.com
Tue Sep 5 16:47:00 EDT 2006


On Tue, Sep 05, 2006 at 03:33:39PM -0400, 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...

I think in the last example, the first space is matching the "not '#'"
clause.  So it's seeing the input as zero spaces followed by a non-'#'
(a space).

Maybe something like this, which uses a notted selector for the commented-out
portion and then moves the substitution pattern into the s/../../ function:

sed -r -e \
  '/^[[:space:]]*#/!s/^.*[[:space:]]xyz.*$/REWRITTEN/'

It seems to pass a few simple cases, I haven't tested it exhaustively.

mm



More information about the gnhlug-discuss mailing list