2013-10-27 161 views
0

我想知道如何从每行的文件中删除一定数量的文本。从文本文件中删除文本

我想不出一种完成这样的任务的方法。

878  57 2 
882  63 1 
887  62 1 
1001 71 0 
1041 79 1 
1046 73 2 

这是文本文件的样子,但我只想要左边的数字。我无法手动右边的2行,因为有超过16,000行。

左边的数字也改变了长度,所以我无法阅读它们的长度。

我也不确定数字之间用什么字符分隔,它可能是制表符。

任何人有什么想法我可以尝试?

如果你想看看文本文件,在这里:http://pastebin.com/xyaCsc6W

回答

3
var query = File.ReadLines("input.txt") 
    .Where(x => char.IsDigit(x.FirstOrDefault())) 
    .Select(x => string.Join("", x.TakeWhile(char.IsDigit))); 

File.WriteAllLines("output.txt", query); 
+0

我不是这样的C#太常见了,但希望在适当的时候,我将有回升这起来了。这工作完美,非常有效。 – Aidan

+0

如果您不知道这一点。仅供参考,这仅仅是Linq和Lambda表达。用这些关键字搜索 –

0
string line; 
using (var sr = new StreamReader(@"E:\test1.txt")) 
{ 
    using (var sw = new StreamWriter(@"E:\test1.tmp")) 
    { 
     while (!sr.EndOfStream) 
     { 
      line = sr.ReadLine(); 
      line = Regex.Match(line, @"([\d]*)").Groups[1].Value; 
      sw.WriteLine(line); 
     } 
    } 
} 
File.Replace(@"E:\test1.tmp", @"E:\test1.txt", null); 
0

你可以这样做:

var col = 
from s in File.ReadAllLines(input_file_name); 
select s.Split(" ".ToCharArray())[0]; 

注:拆分(”“)我有一个空格和一个制表符。

0

你也可以做到这一点,这将给你的文本文件只有左(列)字符(数字/字母)的结果的列表:

var results = File.ReadAllLines("filename.txt") 
       .Select(line => line.Split('\t').First()) 
       .ToList(); 

它看起来像文本文件分隔通过标签。

要保存结果列表返回到一个文本文件中添加除下列内容:

File.WriteAllLines("results.txt", results.ToArray()); 
0
 StringBuilder sb = new StringBuilder(); 
     //read the line by line of file.txt 
     using (StreamReader sr = new StreamReader("file.txt")) 
     { 
      String line; 
      // Read and display lines from the file until the end of 
      // the file is reached. 
      while ((line = sr.ReadLine()) != null) 
      { 
       //for each line identify the space 
       //cut the data from beginning of each line to where it finds space 
       string str = line.Substring(0, line.IndexOf(' ')); 

       //Append each modifed line into string builder object 
       sb.AppendLine(str); 

      } 
     } 

     //Create temp newfile 
     using (File.Create("newfile.txt")) 
     { 
      //create newfile to store the modified data 
     } 

     //Add modified data into newfile 
     File.WriteAllText("newfile.txt",sb.ToString()); 

     //Replace with new file 
     File.Replace("newfile.txt", "file.txt", null);