【发布时间】:2017-03-22 09:59:22
【问题描述】:
我正在寻找一种从 Windows 中的文本文件中删除空字符的快速方法。 使用 Notepad++ 并在所有文档(as described here) 中用任何内容替换“\0”的解决方案不适用于非常大的文件。我的大约 180M,notepad++ 被无限地卡住试图完成这项工作。
【问题讨论】:
我正在寻找一种从 Windows 中的文本文件中删除空字符的快速方法。 使用 Notepad++ 并在所有文档(as described here) 中用任何内容替换“\0”的解决方案不适用于非常大的文件。我的大约 180M,notepad++ 被无限地卡住试图完成这项工作。
【问题讨论】:
我知道这是一篇旧帖子,但我认为它对其他人有用。 这种方法仅在要删除的空值位于行尾时才有效(在我的情况下,我的行长 1000+,最后有 600 个空字符)。
只需复制整个内容,并将其粘贴到新的文件选项卡上,记事本会自动替换空格中的所有空值。然后只需保存使用 ctrl+space+s 修剪所有行。
希望对你有帮助
【讨论】:
这是我为 Windows 找到的解决方案。想法是将this solution 从 UNIX 导入到 Windows。
1) 下载并安装CoreUtil,它是用于 Windows 的基本文件、shell 和文本操作实用程序的集合。
在 windows 7 中,exec 文件通常安装在 c:\Program Files (x86)\GnuWin32\bin
2) 通过在 cmd 窗口中运行此命令来删除 NULL 字符:
tr -d '\000' <input_file >output_file
示例:
c:\Program Files (x86)\GnuWin32\bin>tr -d '\000' <putty_measurements_1.log >putty_measurements_2.log
【讨论】:
我一直在寻找从大文件中删除尾随 NULL 的工具,但我发现的解决方案不适用于 1GB+ 文件或需要很长时间。因此,我用 C# 设计了自己的,效果很好,这里是:
private void CopyContentsUntilNull(string source, bool keepFileDate = true)
{
string destination = $"{Path.GetDirectoryName(source)}{Path.GetFileNameWithoutExtension(source)}_fixed{Path.GetExtension(source)}";
var sourceDate = File.GetLastWriteTime(source);
int bufferSize = 10000;
var buffer = new byte[bufferSize];
int nullCount = 0;
int readCount;
using (var srcStream = File.OpenRead(source))
using (var dstStream = File.OpenWrite(destination))
{
do
{
readCount = srcStream.Read(buffer, 0, bufferSize);
int bytesToCopy = FindTrailingNull(buffer, readCount);
if (bytesToCopy > 0)
{
if (nullCount > 0)
{
var block = Enumerable.Repeat((byte)0, nullCount).ToArray();
dstStream.Write(block, 0, nullCount);
nullCount = 0;
}
dstStream.Write(buffer, 0, bytesToCopy);
}
nullCount += bufferSize - bytesToCopy;
} while (readCount == bufferSize);
}
if (keepFileDate)
File.SetLastWriteTime(destination, sourceDate);
}
private int FindTrailingNull(byte[] buffer, int readCount)
{
for (int i = readCount - 1; i >= 0; i--)
if (buffer[i] != 0)
return i + 1;
return 0;
}
请注意,某些文件的末尾已经有 NULL,例如 zip 文件(从 2 到 4),因此您可能需要在末尾添加一些直到它工作。这同样适用于 docx、xlsx 等,因为它们也是 zip 文件。
【讨论】: