gpt4 book ai didi

javascript - 批量更新,txt文件名第三行内容(第三行内)

转载 作者:行者123 更新时间:2023-12-02 23:18:24 30 4
gpt4 key购买 nike

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

<小时/>

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

<小时/>

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

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

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

下面是我迄今为止所掌握的批处理目录中的文本文件并获取日期作为名称的内容。 (目前重命名为2015-07-09.txt)..只需获取成员(member)编号和上面后面的名称(也包括逗号)即可添加到新名称之前 - 或将其作为新文件名放在日期方面之前。

<小时/>
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])
}
})
}
}
})

最佳答案

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

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

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

然后您可以在 line3 上进一步执行 replace()split()/join()

关于javascript - 批量更新,txt文件名第三行内容(第三行内),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57059014/

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