如何根据分隔符(|)计数将大.txt文件拆分为2。 [英] How to split a large .txt file into 2 based on delimeter (|) count .

查看:109
本文介绍了如何根据分隔符(|)计数将大.txt文件拆分为2。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我是C#.net的新手。我需要一个程序,根据分隔符(|)将一个大的.txt文件拆分为2。如果一行数据具有< = 60管道分隔符,则它应该转到文件1,如果数据行具有> 60,则它转到文件2.我如何实现。如果可能,请帮帮我。



我尝试过:



我尝试使用批处理脚本,但效率并不高。所以我更喜欢C#。我还没试过。我将很快发布。

Hi ,
I am new to C# .net. I need a program to split a large .txt file into 2 based on delimeter (|) count. If a line of data is having <=60 pipe delimeter it should goes to file 1 , if the line of data is having >60 then it goes to file 2. How i can achieve. Please help me if possible.

What I have tried:

I tried in batch script, but it is not that much efficient. So i prefer C# . I haven't try yet. I will post soon.

推荐答案

见这里:计算字符串中的行数 [ ^ ] - 它是关于行的,但相同的技术(和速度结果)将适用于一行中的管道字符。

使用File.ReadAllLines读取文件,然后处理每一行以获取管道数。
See here: Counting Lines in a String[^] - it's about lines, but the same techniques (and speed results) will work for pipe characters within a line.
Read the file using File.ReadAllLines, then process each line to get the pipe count.


如果输入文件很大,我会使用Streams。您将需要 StreamReader 和两个 StreamWriters 。使用语句将它们放在中,以便在它们超出范围时正确关闭它们。这样的事情。

I’d use Streams for this if the input file is large. You will need a StreamReader and two StreamWriters. Put them inside a using statement so they are closed properly when they go out of scope. Something like this.

const string path = @"C:\temp\Test.txt";
const string pathA = @"C:\temp\testA.txt";
const string pathB = @"C:\temp\testB.txt";
try
{
    using (var streamOutA = new StreamWriter(pathA))
    using (var streamOutB = new StreamWriter(pathB))
    using (var streamReader = new StreamReader(path))
    {
        while (streamReader.Peek() >= 0)
        {
            string line = streamReader.ReadLine();
            if ((line.Count(c => c == '|') > 60))
            {
                streamOutA.WriteLine(line);
            }
            else
            {
                streamOutB.WriteLine(line);
            }
        }
    }
 }
catch (Exception e)
{
    Console.WriteLine("File Exception thrown {0} ", e.Message);
}


这篇关于如何根据分隔符(|)计数将大.txt文件拆分为2。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆