[ILUG] Regex Question
Stephen Reilly
stephen at hkc.ie
Tue Sep 28 12:05:16 IST 2004
> > >>> What I would like to be able to do is replace every
> n'th element
> > >>> with something else. So if n = 3, then the result is:
Ok, so it isn't pretty and may still need work but:
Place the following in a script and chmod +x it. Add checks for
arguments and such.
sed -e "s/\($2\)/\1\n/g" $4 | sed -e :a -e "/$2/!N;s/\n/ /;ta" -e 'P;D'
| sed "0~$1s/$2/$3/g"
Then run it like so:
./scriptname 3 '\(<div class="foo">\)\(<\/div>\)' '\1test\2'
htmlfilename
The script works by adding a linebreak after each match and then
appending non matched lines to the following matched ones. Thereby
giving the final sed statement a file which has one match on each line
and not unmatched lines. It can then work it's magic on every third
line. You should reformat the afterward though to get rid of unsightly
long lines :)
Another method I considered was appending three matching lines
and everything between them and then using -e "s/$2/$3/3" on the result.
That kind of gets messy though too. Perhaps what you want is a nice
little loop with a counter variable and get away from all this one line
piping all over the place nonsence?
Steve
More information about the ILUG
mailing list