20

In file a.txt containing "abc", I want to replace "abc" with "ccccccccccccccccccccc", How to read and replace in R? Thank you!

a.txt contents:

{\rtf1
{\fonttbl{\f1\fmodern\fcharset134;}}
{\info}
\sectd\pgwsxn11907\pghsxn16840\marglsxn1418\margrsxn1418
\margtsxn1440\margbsxn1440\sectdefaultcl
\headery851{\header\pard\qr\fs18\par}
\footery992{\footer\pard\qc\f0\fs18\chpgn\par}
\pard\qc\sb30\sa30\fs21 \par
\trowd\trautofit1\trgaph0\trleft-75\intbl\trqc           
\clbrdrt\brdrs\brdrw30\clbrdrb\brdrs\brdrw10\clvertalc\cellx6993\clbrdrt
\brdrs\brdrw30\clbrdrb\brdrs\brdrw10\clvertalc\cellx13986\clbrdrt\brdrs\brdrw30
\clbrdrb\brdrs\brdrw10\clvertalc\cellx20979
\qc\fs21 x\cell\qc\fs21 y\cell\qc\fs21 z\cell\row
\trowd\trautofit1\trgaph0\trleft-75\trqc                  
\clvertalc\cellx6993\clvertalc\cellx13986
\clvertalc\cellx20979
\qc\fs21 a\cell\qc\fs21 b\cell\qc\fs21 abc\cell\row
\trowd\trautofit1\trgaph0\trleft-75\intbl\trqc   
\clbrdrb\brdrs\brdrw30\clvertalc\cellx6993\clbrdrb\brdrs\brdrw30
\clvertalc\cellx13986\clbrdrb\brdrs\brdrw30\clvertalc\cellx20979
\qc\fs21 d\cell\qc\fs21 e\cell\qc\fs21 f\cell\row
}    
stata
  • 513
  • 2
  • 6
  • 12

2 Answers2

37

It's easy :

  • load your text in R using readLines (or scan)
  • change your pattern using sub or gsub
  • export your text to a text file using writeLines or scan

Example:

tx  <- readLines("~/Desktop/text.txt")
tx2  <- gsub(pattern = "abc", replace = "ccccccccccccccccccccc", x = tx)
writeLines(tx2, con="~/Desktop/text2.txt")

See R Programming wikibooks if you want to know more

Roland
  • 127,288
  • 10
  • 191
  • 288
PAC
  • 5,178
  • 8
  • 38
  • 62
  • Thank you! tx <- readLines("F:/aaaaaaa.txt") Warning message: In readLines("F:/aaaaaaa.txt") : incomplete final line found on 'F:/aaaaaaa.txt' How to avoid Warning message? Thank you! – stata May 05 '14 at 14:45
  • This is a warning, not an error. If you just add a line at the end of your text file, it will be ok. – PAC May 05 '14 at 15:46
3

Original @PAC's variant but without creating variables. It uses the R-base native pipe (R 4.1.0) and the stringr package (a part of the tidyverse).

readLines("~/Desktop/text.txt") |>
  stringr::str_replace(
    pattern = "abc", 
    replace = "ccccccccccccccccccccc") |>
  writeLines(con = "~/Desktop/text2.txt")
malexan
  • 140
  • 1
  • 5