如何反向处理文件以移除位置51处的所有CRLF
解决方案
Python 脚本实现反向处理
因为需要从文件末尾反向处理,我们可以直接读取文件内容后从后往前扫描,精准识别并移除位置51处的自动换行符(\r\n)。
以下是可直接运行的脚本:
def fix_wrapped_lines(file_path, output_path): # 以字节模式读取,避免编码问题,保留原始换行符 with open(file_path, 'rb') as f: content = bytearray(f.read()) crlf = b'\r\n' pos = len(content) - len(crlf) while pos >= 0: # 检查当前位置是否是CRLF if content[pos:pos+2] == crlf: # 计算当前CRLF前的分隔点:往前推50字节,要么是文件开头,要么前一个字节是上一个CRLF的结尾 prev_sep = pos - 50 if prev_sep < 0: pos -= 1 continue if prev_sep == 0 or content[prev_sep-1] == ord(b'\n'): # 移除自动插入的CRLF del content[pos:pos+2] pos -= 1 # 写入处理后的内容 with open(output_path, 'wb') as f: f.write(content) # 替换为你的输入输出文件路径 fix_wrapped_lines('input.txt', 'output.txt')
说明:脚本从文件末尾向前遍历,只删除符合“前一段刚好50字符”规则的CRLF,保留空行和其他正常换行。
Node.js 脚本实现反向处理
如果更熟悉Node.js,可用以下脚本:
const fs = require('fs'); function fixWrappedLines(inputPath, outputPath) { const content = fs.readFileSync(inputPath); const crlf = Buffer.from('\r\n'); const contentArr = [...content]; let pos = contentArr.length - crlf.length; while (pos >= 0) { if (contentArr[pos] === crlf[0] && contentArr[pos+1] === crlf[1]) { const prevSep = pos - 50; if (prevSep < 0) { pos--; continue; } if (prevSep === 0 || contentArr[prevSep - 1] === crlf[1]) { // 删除当前CRLF contentArr.splice(pos, 2); } } pos--; } fs.writeFileSync(outputPath, Buffer.from(contentArr)); } // 替换为你的文件路径 fixWrappedLines('input.txt', 'output.txt');
Cmder(Cygwin)命令行方案
利用Cygwin自带的Perl工具处理,保存以下代码为fix_lines.pl:
open my $in, '<:raw', $ARGV[0] or die $!; local $/; my $content = <$in>; close $in; # 匹配每50字符后的自动换行CRLF并移除 $content =~ s/(?<=^.{50}|\r\n.{50})\r\n//g; open my $out, '>:raw', $ARGV[1] or die $!; print $out $content; close $out;
在Cmder中运行命令:
perl fix_lines.pl input.txt output.txt
内容的提问来源于stack exchange,提问作者Bard RT
相关产品推荐
相关产品推荐

