js怎么对txt文本里面的内容进行筛选只获取该行有req:或ans:的行的数据写到另一个txt文件中
可以使用Node.js的文件系统模块(fs)来实现对txt文本内容的筛选和写入操作。具体步骤如下:
- 引入fs模块,使用fs的readFileSync方法读取原始txt文件的内容。
- 将读取得到的内容按行分割成数组,可以使用split('\n')方法。
- 使用数组的filter方法筛选出包含"req:"或"ans:"的行,可以使用includes方法。
- 将筛选得到的行数组使用join('\n')方法拼接成字符串。
- 使用fs的writeFileSync方法将筛选后的内容写入到另一个txt文件中。
以下是一个示例代码:
const fs = require('fs');
const inputFilename = 'input.txt';
const outputFilename = 'output.txt';
// 读取原始txt文件的内容
const content = fs.readFileSync(inputFilename, 'utf-8');
// 按行分割内容为数组
const lines = content.split('\n');
// 筛选包含"req:"或"ans:"的行
const filteredLines = lines.filter(line => line.includes('req:') || line.includes('ans:'));
// 拼接筛选后的行为字符串
const outputContent = filteredLines.join('\n');
// 将筛选后的内容写入到另一个txt文件中
fs.writeFileSync(outputFilename, outputContent, 'utf-8');
console.log('筛选完成');
在运行以上代码之前,需要将input.txt文件放在同一目录下,并确保该文件中包含要筛选的内容。运行代码后,会将筛选后的内容写入到output.txt文件中
原文地址: https://www.cveoy.top/t/topic/iqr0 著作权归作者所有。请勿转载和采集!