For example, there is a plain text document on the slave table in which there are numbers from 0 to 100 line by line (1,2,3, ..., 99,100). And also there is another txt doc. in which the words are the same line by line, there, for example, the word "map". Question: how through software to replace this word map (all strings that are in the doc with line numbers from the first txt?

That is, the result should be:

static void map1() ->1 static void map2() ->2 ... static void map100() ->100 

In fact, the whole line is where there is a static void map_ and which digit is replaced by 1,2,3 .... That is, in the end I will receive line by line replacement with a number

  • Unclear. Here I find, for example, in the second file map3 and map4 . And in the first there are only the numbers 1, 4 and 5. What should happen at the exit? - VladD
  • not map3 and map4 a will be static void map_ and number ..... The output should be static void1 (), static void4 (), static void5 () ... That is, all the lines that have the word map ("map" is not "map4" and "map"), changes to the numbers 1,4,5 (these numbers are written down in line-by-line and their number is not 3 a> 3 - komra23
  • that is to say it should be: static void map () static void map () ... static void map () take the numbers from txt and be: static void 1 () static void 2 () ... static void 100 () - komra23

1 answer 1

If I understand the problem correctly, the following will do:

 static void Main(string[] args) { var replacements = File.ReadLines("1.txt"); var inputLines = File.ReadLines("2.txt"); var regex = new Regex(@"map(\d+)", RegexOptions.Compiled); var outputLines = Replace(inputLines, regex, replacements); File.WriteAllLines("2_modified.txt", outputLines); } static IEnumerable<string> Replace( IEnumerable<string> haystack, Regex needle, IEnumerable<string> with) { using (var it = with.GetEnumerator()) { foreach (var s in haystack) { var result = s; foreach (Match match in needle.Matches(result).Cast<Match>().Reverse()) { var group = match.Groups[1]; if (!it.MoveNext()) throw new InvalidOperationException("Недостаточно строк в первом файле"); result = result.Substring(0, group.Index) + it.Current + result.Substring(group.Index + group.Length); } yield return result; } } } 

For the case when there are many replacement files, do this:

 var replacementFiles = new[] { "1a.txt", "1b.txt" }; var replacements = replacementFiles.SelectMany(File.ReadLines); 

and further in the text.

For a specific directory will go, for example,

 var replacementDirectory = @"С:\"; var replacementFiles = Directory.EnumerateFiles(replacementDirectory, "*.txt"); 

(the path and mask need, of course, correct).

  • Comments are not intended for extended discussion; conversation moved to chat . - Nick Volynkin
  • @VladD komenty in chat - komra23
  • SOMEONE CAN READ OUT ANSWER ?? - komra23