Notepad++下使用CS Script批量修改大文件行内容的技术求助
Notepad++下使用CS Script批量修改大文件行内容的技术求助
嗨,我来帮你搞定这个需求!既然你之前习惯用Excel VBA但文件太大扛不住,用CS Script处理大文本文件确实是个高效的选择,我给你准备了适配的脚本,还有详细的使用说明:
需求拆解
你的核心需求很清晰:
- 从文件的第二行开始遍历所有行
- 按分号
;拆分每行的列内容 - 检查倒数第二列的数值是否为负数
- 如果是负数,将该行的最后三列全部改为
0 - 其他行保持原样
脚本实现(适合常规大小文件)
这个版本一次性读取文件到内存,处理起来简单直接,适合几GB以内的文件:
using System; using System.IO; class Program { static void Main(string[] args) { // 替换成你的目标文件路径,Windows路径建议用@前缀避免转义问题 string targetFilePath = @"C:\Your\File\Location\your_data_file.txt"; string[] allLines = File.ReadAllLines(targetFilePath); // 从第二行开始处理(数组索引从0开始,所以i从1起步) for (int i = 1; i < allLines.Length; i++) { string currentLine = allLines[i]; // 按分号拆分列,保留所有拆分结果 string[] columns = currentLine.Split(';'); // 先检查列数是否符合预期,避免索引越界报错 if (columns.Length >= 9) { // 尝试将倒数第二列转为浮点数,兼容不同格式的数值 if (double.TryParse(columns[columns.Length - 2], out double checkValue)) { // 判断数值是否为负数 if (checkValue < 0) { // 修改最后三列为0 columns[columns.Length - 3] = "0"; columns[columns.Length - 2] = "0"; columns[columns.Length - 1] = "0"; // 重新拼接成一行 allLines[i] = string.Join(";", columns); } } } } // 将处理后的内容写回原文件,**一定要先备份原文件!** File.WriteAllLines(targetFilePath, allLines); Console.WriteLine("文件处理完成!"); } }
超大文件适配版(逐行处理,低内存占用)
如果你的文件特别大(比如几十GB),上面的版本可能会占用过多内存,这个逐行读写的版本更适合:
using System; using System.IO; class Program { static void Main(string[] args) { string inputPath = @"C:\Your\File\Location\original_data.txt"; // 先写到临时输出文件,确认没问题再替换原文件,更安全 string outputPath = @"C:\Your\File\Location\processed_data.txt"; using (StreamReader reader = new StreamReader(inputPath)) using (StreamWriter writer = new StreamWriter(outputPath)) { // 第一行直接写入,不做处理 string firstLine = reader.ReadLine(); if (firstLine != null) { writer.WriteLine(firstLine); } // 逐行读取并处理剩余内容 string currentLine; while ((currentLine = reader.ReadLine()) != null) { string[] columns = currentLine.Split(';'); if (columns.Length >= 9) { if (double.TryParse(columns[columns.Length - 2], out double checkValue)) { if (checkValue < 0) { columns[columns.Length - 3] = "0"; columns[columns.Length - 2] = "0"; columns[columns.Length - 1] = "0"; currentLine = string.Join(";", columns); } } } writer.WriteLine(currentLine); } } Console.WriteLine("处理完成!请先检查输出文件:" + outputPath); // 确认无误后,可以取消下面两行注释来替换原文件 // File.Copy(outputPath, inputPath, overwrite: true); // File.Delete(outputPath); } }
Notepad++中运行脚本的步骤
- 打开Notepad++,新建空白文件,将上面的代码粘贴进去
- 保存文件为
.cs后缀,比如ProcessFile.cs - 确保你已经安装了CS Script的Notepad插件(如果没装,打开Notepad的「插件」→「插件管理」,搜索CS Script并安装)
- 点击「插件」→「CS Script」→「Execute Script」,或者按对应的快捷键运行脚本
- 重要提醒:运行前一定要备份你的原始文件,避免意外修改无法恢复!
如果运行过程中遇到报错(比如路径不对、格式异常),可以告诉我具体的错误信息,我再帮你调整细节~
备注:内容来源于stack exchange,提问作者Intelect
相关产品推荐
相关产品推荐

