Sed replacing half of the matched expressions

Sed replacing half of the matched expressions

Post by Antoine Le » Tue, 06 Nov 2001 09:39:09



Hi!
Can you help with this lil problem:
I've got lines that look like this

1: regex bla bla ... .. bla regex bla bla
2: bla bla regex bla ... regex

I want to replace the /regex/ with /regex2/ only the first on the
line, not the second
Or one on two
Or the only the odd-numbered apparitions of "regex"
..
Each line contains exactly 2 "regex"

Thanks for your help

 
 
 

Sed replacing half of the matched expressions

Post by Michael Heimin » Tue, 06 Nov 2001 10:08:22



01:39:

> Hi!
> Can you help with this lil problem:
> I've got lines that look like this

> 1: regex bla bla ... .. bla regex bla bla
> 2: bla bla regex bla ... regex

> I want to replace the /regex/ with /regex2/ only the first on the
> line, not the second
> Or one on two
> Or the only the odd-numbered apparitions of "regex"
> ..
> Each line contains exactly 2 "regex"

> Thanks for your help



sed 's/regex/regex1/' infile > outfile

Michael Heiming

 
 
 

Sed replacing half of the matched expressions

Post by Bill Marcu » Tue, 06 Nov 2001 09:41:29



>Hi!
>Can you help with this lil problem:
>I've got lines that look like this

>1: regex bla bla ... .. bla regex bla bla
>2: bla bla regex bla ... regex

>I want to replace the /regex/ with /regex2/ only the first on the
>line, not the second
>Or one on two
>Or the only the odd-numbered apparitions of "regex"
>..
>Each line contains exactly 2 "regex"

s/regex/regex2/
By default, sed replaces the first "regex" on each line.  If you wanted
to replace every "regex" you would write 's/regex/regex2/g'
 
 
 

Sed replacing half of the matched expressions

Post by Stephane CHAZEL » Thu, 08 Nov 2001 05:35:03


if you want
abababababababab
to be converted to
abababababababab

sed -e s/a/c

to be converted to
abababcbabababab

sed -e s/a/c/4

to be converted to
abababababababcb

sed -e s/\(.*\)a/\1c/

to be converted to
cbcbcbcbcbcbcbcb

sed -e s/a/c/g

to be converted to
cbabcbabcbabcbab

sed -e s/aba/cba/g

Or, more complicated:

12 foo 123 qsd qsd 456 sssssgf 1 sdf 45 fg 56 dfg 67 dfg 123
to be converted to
Z foo 123 qsd qsd Z sssssgf 1 sdf Z fg 56 dfg Z dfg 123
(one number out of 2 changed into Z)

sed -e 's/[0-9][0-9]*\([^0-9]*[0-9]*\)/Z\1/g'

--
Stphane