gpt4 book ai didi

r - 在文本文件中的特定行之间粘贴文本? (右)

转载 作者:行者123 更新时间:2023-12-02 03:25:16 24 4
gpt4 key购买 nike

假设我有这个 .txt 文件:

here is line 1
here is line 2
here is line 3
here is line 4

我想将此字符串粘贴到第 3 行和第 4 行之间:

here is line 3.5

我怎样才能做到这一点?起初我想也许写下我下面的内容可能会起作用,但它只会删除其他行。

cat("",
"",
"",
"this is line 3.5",sep="\n", file = "file.txt")

最佳答案

这是一种方法:定义一个函数以在特定位置插入字符串,然后将该函数应用于您的数据,然后将文件写回磁盘。

# if the text is from a file `fname` you'd use `dat <- readLines(fname)` 
dat <- c("here is line 1",
"here is line 2",
"here is line 3",
"here is line 4")

text_to_insert <- "here is line 3.5"

insert_line_at <- function(dat, to_insert, insert_after){
pre <- dat[1:insert_after]
post <- dat[(insert_after+1):length(dat)]
return(c(pre, to_insert, post))
}

dat_inserted <- insert_line_at(dat, text_to_insert, insert_after=3)

然后将新文本写回到您想要的任何文件中:

writeLines(dat_inserted, "output_filename.txt")

如果您正在处理非常大的文件,那么最好使用命令行实用程序,例如 sedawk 。但如果你想坚持使用 R,那么上面的方法是一个干净+简单的方法。

请注意,您可以插入任意长度(包括零)的字符向量 to_insert ——而不仅仅是示例中的单个字符串。因此,将该函数命名为 insert_lines_at() 可能更合适。

关于r - 在文本文件中的特定行之间粘贴文本? (右),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53601813/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com