在特定搜索词后搜索文本文件,并在输出中更改结果

时间:2018-01-30 11:39:14

标签: c# parsing text

我有一个格式为

的文本文件
  

姓名Harr​​y.Potter

     

编号123.123234

     

姓名Lisa.Simpson

     

编号+44.123234

如果以<{1}}开头,我希望将点(Name)换成空白('.')。

如何仅更改以' ' Name开头的行中的点?

我在代码的其他部分使用NumberSystem.IO.File.WriteAllLines,因此如果此功能可以用类似的方式完成,那将是我的好处。

2 个答案:

答案 0 :(得分:2)

非常直接:如果行StartsWith "Name" ...

var data = File
  .ReadLines(@"c:\MyFile.txt")
  .Select(line => line.StartsWith("Name")
     ? line.Replace('.', ' ') // change '.' to space if starts with Name
     : line)                  // otherwise, leave intact
  .ToArray(); // Materialization if you want to write back to the same file

File.WriteAllLines(@"c:\MyFile.txt", data);

答案 1 :(得分:0)

尝试这样的事情:

//read all lines
var lines = File.ReadAllLines(@"c:\temp\test.txt");
//iterate through all lines
for (int i=0; i<lines.Length; i++)
{
    //check if line starts with name, and if it does, replace dot with space
    if (lines[i].StartsWith("Name"))
        lines[i] = lines[i].Replace(".", " ");
}
//write lines bact to file
File.WriteAllLines(@"c:\temp\test.txt", lines);