You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在R语言中循环遍历并批量编辑文本文件的实现方法

批量处理.inp文件的R实现方案

准备工作

先确认你的文件名列表,可直接定义为如下向量:

filenames <- c(
  "meanimpactscript.inp", 
  "measinvarscript_IBR1.inp", 
  "measinvarscript_IBR10.inp", 
  "measinvarscript_IBR13.inp",
  "measinvarscript_IBR2.inp", 
  "measinvarscript_IBR4.inp", 
  "measinvarscript_IBR5.inp", 
  "measinvarscript_IBR7.inp", 
  "varimpactscript.inp"
)

方案一:所有文件匹配统一关键词

如果所有文件都需要查找相同的关键词(比如你示例中的"ETA BY IBR13"),用以下代码批量处理:

  1. 定义单个文件的处理函数:
process_file <- function(file_path) {
  # 读取文件内容
  content <- readLines(file_path)
  # 定位目标行位置
  ix <- grep("ETA BY IBR13", content)
  # 在目标行插入指定文本
  modified_content <- append(content, "thresholds", ix)
  # 拼接内容并覆盖原文件
  modified_str <- paste(modified_content, collapse = "\n")
  writeLines(modified_str, con = file_path)
}
  1. 批量执行:
lapply(filenames, process_file)

方案二:根据文件名动态匹配关键词

如果measinvarscript_IBRx.inp这类文件需要匹配对应编号的关键词(比如measinvarscript_IBR1.inp匹配"ETA BY IBR1"),用动态匹配方式:

  1. 定义带动态匹配的处理函数(需stringr包支持):
process_file_dynamic <- function(file_path) {
  content <- readLines(file_path)
  
  # 从文件名提取IBR编号
  ibr_number <- stringr::str_extract(file_path, "IBR\\d+")
  # 构造匹配关键词,非IBR开头的文件用默认关键词
  pattern <- if (!is.na(ibr_number)) {
    paste0("ETA BY ", ibr_number)
  } else {
    "ETA BY IBR13" # 可按需修改mean/var文件的默认关键词
  }
  
  ix <- grep(pattern, content)
  modified_content <- append(content, "thresholds", ix)
  modified_str <- paste(modified_content, collapse = "\n")
  writeLines(modified_str, con = file_path)
}
  1. 批量执行(未安装stringr需先安装):
# install.packages("stringr")
lapply(filenames, process_file_dynamic)

注意事项

  • 上述代码会直接覆盖原文件,操作前务必备份所有目标文件,避免数据丢失。
  • 如果文件中找不到匹配的关键词,append会将"thresholds"插入到文件末尾,可根据需求调整该场景的处理逻辑。

内容的提问来源于stack exchange,提问作者wooden05

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 20:10:48