RobinLovelace
RobinLovelace

Reputation: 4987

Insert block of text into a file at a specific line number in R

I am using script to convert a Markdown file generated with knitr into tex:

  mess <- paste('pandoc -f markdown -t latex -s -o', "intro-spatial.tex", 
          "intro-spatial.md")
  system(mess) # create latex file

This works great, but I need to do some additional tweaks to the latex doc. to make it look nice. I can do this in a text editor, but because it needs to compile many times, makes sense to script it. For example, to make the figures the right size I add:

mess <- paste("sed -i -e 's/width=\\maxwidth/[width=8cm/g' intro-spatial-rl.tex")
system(mess)

What I cannot figure out is how to insert a big block of text. Specifically, how to I add this after line n. 62? (See here for related question.)

\author{
   x, y\\
  \texttt{[email protected]}
  \and
  x, y\\
  \texttt{[email protected]}
}
\title{Introduction to Spatial Data and ggplot2}

It's possible that I'm using completely the wrong approach here. If so let me know!

Upvotes: 2

Views: 952

Answers (1)

B.Mr.W.
B.Mr.W.

Reputation: 19628

Just to answer how to insert paragraph into a file at specific line number: idx :)

The code below will insert the paragraph you have given after line 6.

# text will be inserted after the line
idx <- 5
# open the file and read in all the lines 
conn <- file("test.txt")
text <- readLines(conn)
block <- "\\author{
   x, y\\
  \\texttt{[email protected]}
  \\and
  x, y\\
  \\texttt{[email protected]}
}
\\title{Introduction to Spatial Data and ggplot2}"
text_block <- unlist(strsplit(block, split='\n'))
# concatenate the old file with the new text
mytext <- c(text[1:idx],text_block,text[(idx+1):length(text)]) 
writeLines(mytext, conn, sep="\n")
close(conn)

Here I have modified your paragraph because your \t \a ..etc. will be evaluated as tab ... I double escaped them to make it work as the raw text. I am also looking forward to knowing how to handle the escape easily. Like what you have asked in another post.

Upvotes: 2

Related Questions