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
}
The sub() function in R is used to replace the string in a vector or a data frame with the input or the specified string.
R can read data from a variety of file formats—for example, files created as text, or in Excel, SPSS or Stata. We will mainly be reading files in text format . txt or . csv (comma-separated, usually created in Excel).
Read Lines from a File in R Programming – readLines() Function. readLines() function in R Language reads text lines from an input file. The readLines() function is perfect for text files since it reads the text line by line and creates character objects for each of the lines.
It's easy :
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
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With