首页 > 解决方案 > 批量更新,txt文件名与第三行内容(第三行内)

问题描述

我已经设法形成一个正则表达式来搜索在文件中找到的日期格式,并使用其中找到的每个日期.txt批量更新文件的每个名称。.txt但是,在日期出现之前获取会员 ID 和会员姓名的新要求。


我不愿意为此使用正则表达式,因为格式似乎不够独特。我在想抓住文本文件“第 3 行”上的所有内容,并在名称前添加(在日期之前)。


例如 .txt 文件的前 3 行如下所示:

MEMBER    
-------- ---------------
9999199  RON, CAPTAIN // this is line 3

即所需的新文件名/输出: 9999199_RON,CAPTAIN_2015-07-09.txt

以下是我到目前为止批量处理目录中的文本文件并将日期作为名称的内容。(当前重命名为2015-07-09.txt) .. 只需要获取成员编号和上面的名称(包括逗号)以添加到新名称之前 - 或作为新文件名放在日期方面之前。


const fs = require('fs')
const path = require('path')

let dir = './'

fs.readdir(dir, {
  encoding: 'utf8',
  withFileTypes: true
}, (err, files) => {
  if (err) {
    // Error happened when reading the directory
    console.error(err)
    return
  }
  for (const file of files) {
    if (!file.isFile()) {
      // Directory or block device?
      continue;
    }

    // Read file contents
    let fileContents = fs.readFileSync(path.join(dir, file.name), 'utf8')
    let dateMatches = fileContents.match(/[12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])/)
    if (dateMatches) {
      // There is a date here
      fs.rename(path.join(dir, file.name), path.join(dir, dateMatches[0]), (err) => {
        if (err) {
          console.error(err)
          // Do your error handling stuff here...

          return
        } else {
          console.log('Renamed', file.name, 'to', dateMatches[0])
        }
      })
    }
  }
})

标签: javascriptnode.jsregexbatch-rename

解决方案


尝试fileContents使用分隔符拆分\n,并将其限制为3块。

let [,,line3] = fileContents.split('\n', 3); 

if(line3) {
    // do the work
} else {
    // error handling, where file is too short, less than 3 lines.
}

然后你可以做进一步replace()split()/ join()online3


推荐阅读