如何将特定行从一个文件复制到另一个文件? [英] How to copy specific lines from one file to another?

查看:126
本文介绍了如何将特定行从一个文件复制到另一个文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大约3000行的文本文件.有些行以数字开头,有些则以文本开头.例如:

I have a text file with about 3000 lines. Some lines start with numbers and some with text. For example:

以数字开头的行:

001一些文字

0017一些文字

8条文字...

以文本开头的行:

一些文字

一些文字...

我想将以数字开头的行复制到result.text.

I want to copy lines that start with numbers to result.text.

以文本开头的行到log.txt.

Lines that start with text to log.txt.

非常感谢.

推荐答案

可以在一个语句中完成一个文件

It can be done in one statement for one file

WriteAllLines("new file", 
    ReadLines("source file")
    .Where(line => line.Lenth > 0 && Char.IsDigit(line[0]))
);

请注意,它在内部逐行工作,即一次内存中只有一行.从处理的输入中读取一行并将其写入输出,然后从下一行等等.这是因为这些方法与IEnumerable<string>一起使用.例如,IEnumerable不会像将文件读入数组那样缓冲整个文件.

Note that it works on a line-by-line basis internally, i.e. there will be only one line at a time in memory. One line will be read from input processed and written to the output, then the next line and so on. This is because these methods work with IEnumerable<string>. IEnumerable does not buffer the whole file as would be the case if you read the file into an array, for instance.

对于两个输出文件,您将不得不重复两次.因此,我建议采用以下方法,该方法只读取输入文件一次:

You would have to repeat this twice for the two output files. Therefore I suggest the following approach, which reads the input file only once:

using (var log = CreateText("log.txt"))
using (var result = CreateText("result.txt")) {
    foreach (string line in ReadLines("source file")) {
        if (line.Length > 0) {
            if (Char.IsDigit(line[0])) {
                result.WriteLine(line);
            } else {
                log.WriteLine(line);
            }
        }
    }
}

第二种方法也不缓冲文件.

This second approach does not buffer the file either.

这篇关于如何将特定行从一个文件复制到另一个文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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