Volodymyr Gnatiuk Volodymyr Gnatiuk - 3 months ago 16
C# Question

Edit specific word in specific line

I know this has been asked a few times, but I'm need a fast way to do this in files with different size (small and large files).

I need to edit scale factor in sat(txt) file. This is a first number in third line:


700 104 1 0 16 Autodesk AutoCAD 19 ASM 221.0.0.1871 NT 24 Tue

Aug 16 09:02:14 2016

1000 9.9999999999999995e-007 1e-010

Answer

I suggest extracting a method and Linq:

private static String MyEditLine(string value) {
  var items = value.Split(new char[] { ' ' }, 2);

  items[0] = "2000"; // let's change 1000 into 2000

  return string.Join(" ", items);
}

...

var target = File
  .ReadLines(@"C:\MyFile.txt")
  .Select((line, index) => index != 2
     ? line
     : MyEditLine(line))
  .ToList(); 

File.WriteAllLines(@"C:\MyFile.txt", target);