javascript - 批量更新,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])
}
})
}
}
})
解决方案
尝试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
推荐阅读
- ios - 如何让我的查看器控制器全屏显示?
- azure-functions - 尝试连接到本地数据库时在本地执行 Azure 功能时出现异常
- javascript - 根据显示信息
地点 - java - Spring @Scheduled 方法 SecurityContext
- python - 使用 pylam 检查进口订单
- azure - Azure 环境配置搞砸了 AJAX 调用?(棱镜、反应、GraphQL、GatsbyJS)
- webpack - 如何为 webpack-hot-middleware 设置上下文
- java - 号码识别显示错误答案
- c# - 如何在 FluentAssertions 中使用方法
- codenameone - Codenameone - 何时将 callSerally 与对话框一起使用?