[R] replace text at certain positions in a file

RINNER Heinrich HEINRICH.RINNER at tirol.gv.at
Tue Nov 2 11:20:57 CET 2010


Hello,

thanks again for this nice solution using sub and regular expressions!
However, in real life I have to overwrite more than two positions with blanks (say 50 or so), so I was trying to modify this in the following way:

> s <- c("ab34cd78e", "fg3 hi78j")

# your suggestion (works perfectly for the simple case):
> sub("^(..)..(..)..", "\\1  \\2  ", s)
[1] "ab  cd  e" "fg  hi  j"

# gereralizing the pattern (works as well):
> sub("^(.{2}).{2}(.{2}).{2}", "\\1  \\2  ", s)
[1] "ab  cd  e" "fg  hi  j"

# generalizing the replacement (doesn't work):
>  sub("^(.{2}).{2}(.{2}).{2}", "\\1 {2}\\2 {2}", s)
[1] "ab {2}cd {2}e" "fg {2}hi {2}j"

Apparently, " {2}" ist not interpreted as a string with two blanks ("  ") in the replacement part, so something is wrong in my expression there. I just can't figure out what...

Kind regards
Heinrich.


> -----Ursprüngliche Nachricht-----
> Von: Gabor Grothendieck [mailto:ggrothendieck at gmail.com]
> Gesendet: Donnerstag, 28. Oktober 2010 13:40
> An: RINNER Heinrich
> Cc: r-help at stat.math.ethz.ch
> Betreff: Re: [R] replace text at certain positions in a file
>
>
> On Thu, Oct 28, 2010 at 5:26 AM, RINNER Heinrich
> <HEINRICH.RINNER at tirol.gv.at> wrote:
> > Hello,
> >
> > I am working with R version 2.10.1 under windows.
> > In a text file, I need to replace all characters at certain
> column positions with blanks.
> > For example, say the file contains two lines and looks like this:
> >
> > ab34cd78e
> > fg3 hi78j
> >
> > I'd like to replace everything at positions 3-4 and 7-8
> with blanks, so the output should be:
> >
> > ab  cd  e
> > fg  hi  j
> >
> > [I'm not sure if this is really an R question(?), solutions
> outside of R - maybe via shell() or so - are welcome!]
> >
>
> Try this:
>
> > s <- c("ab34cd78e", "fg3 hi78j")
> > sub("^(..)..(..)..", "\\1  \\2  ", s)
> [1] "ab  cd  e" "fg  hi  j"
>
>
> --
> Statistics & Software Consulting
> GKX Group, GKX Associates Inc.
> tel: 1-877-GKX-GROUP
> email: ggrothendieck at gmail.com
>



More information about the R-help mailing list