【问题标题】:Insert block of text into a file at a specific line number in R在 R 中的特定行号处将文本块插入文件中
【发布时间】:2013-12-14 17:00:03
【问题描述】:

我正在使用脚本将knitr生成的Markdown文件转换为tex:

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

这很好用,但我需要对乳胶文档做一些额外的调整。让它看起来nice。我可以在文本编辑器中执行此操作,但因为它需要多次编译,所以编写脚本很有意义。例如,为了使数字尺寸合适,我添加了:

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

我不知道如何插入一大块文本。具体来说,如何在第 n 行之后添加它。 62? (相关问题请参见here。)

\author{
   x, y\\
  \texttt{x@y.com}
  \and
  x, y\\
  \texttt{x@y.com}
}
\title{Introduction to Spatial Data and ggplot2}

我可能在这里使用了完全错误的方法。如果有,请告诉我!

【问题讨论】:

    标签: r text system


    【解决方案1】:

    只是回答如何将段落插入到特定行号的文件中:idx :)

    下面的代码将在第 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{x@y.com}
      \\and
      x, y\\
      \\texttt{x@y.com}
    }
    \\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)
    

    这里我修改了你的段落,因为你的 \t \a ..etc。将被评估为制表符...我对它们进行了双重转义以使其作为原始文本工作。我也很期待知道如何轻松处理逃跑。就像你在另一篇文章中问的那样。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-29
      • 2017-04-23
      • 2014-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多