如何在文本文件中逐行读取和替换字符串?

时间:2015-08-28 15:18:11

标签: c# file

我有一个文本文件,上面写着:

INSERT INTO `shops` VALUES ('', '3', '1000000', '0');
INSERT INTO `shops` VALUES ('', '3', '1000010', '0');
INSERT INTO `shops` VALUES ('', '3', '1000020', '0');
INSERT INTO `shops` VALUES ('', '3', '1000030', '0');
INSERT INTO `shops` VALUES ('', '3', '1001000', '0');

请注意每行第一个键是''。对于每一行,我想找到'',并用数字(从1开始)替换它,然后在它转到下一行时加1,如下所示:

INSERT INTO `shops` VALUES ('1', '3', '1000000', '0');
INSERT INTO `shops` VALUES ('2', '3', '1000010', '0');
INSERT INTO `shops` VALUES ('3', '3', '1000020', '0');
INSERT INTO `shops` VALUES ('4', '3', '1000030', '0');
INSERT INTO `shops` VALUES ('5', '3', '1001000', '0');

我一直试图这样做几个小时,但我失败了。

这就是我一直在想的(我知道这远非正确,但我在c#中并不精通,所以也许你们其中一人可以帮我提出正确的代码) :

string text = File.ReadAllText("C:\\Users\\Donavon\\Desktop\\old.sql");

int i = 0;
text = text.Replace("('',", "('" + i + "',");
i++;
File.WriteAllText("C:\\Users\\Donavon\\Desktop\\new.sql", text);

感谢您的帮助,非常感谢

9 个答案:

答案 0 :(得分:7)

你会想要按照以下方式做点什么:

#topper

使用File.ReadLines枚举这些行,这样就不会出现大文件的内存异常

答案 1 :(得分:5)

您可以单独阅读这些行:

string text = "";
using (StreamReader sr = new StreamReader("C:\\Users\\Donavon\\Desktop\\old.sql"))
{
    int i = 0;
    do
    {
        i++;
        string line = sr.ReadLine();
        if (line != "")
        {
            line = line.Replace("('',", "('" + i + "',");
            text = text + line + Environment.NewLine;
        }
    } while (sr.EndOfStream == false);
}
File.WriteAllText("C:\\Users\\Donavon\\Desktop\\new.sql", text);

答案 2 :(得分:3)

这里不是代码解决方案,但如果我必须做这样的事情并且我知道角色的位置总是相同的(就像你的例子),我会选择使用Notepad ++进行快速编辑并且不要#39学习编程语言。

  1. 将光标放在''之间。并使用快捷键ALT + C

  2. 选择选项"要插入的编号",填写初始编号(1)并增加(1)

答案 3 :(得分:1)

   var lines = File.ReadAllLines(@"D:\temp\old.sql");

    for (int i = 0; i < lines.Count(); ++i)
         lines[i] = lines[i].Replace("\'\'", string.Format("\'{0}\'", i + 1));

    File.WriteAllLines(@"D:\temp\new.sql", lines);

答案 4 :(得分:0)

我认为这会奏效。从MSDN得到了大部分内容。

  int counter = 1;
        string line;

        // Read the file and display it line by line.
        System.IO.StreamReader file = 
           new System.IO.StreamReader("C:\\Users\\Donavon\\Desktop\\old.sql");

        while((line = file.ReadLine()) != null)
        {
           line.Replace("('',", "('" + counter.ToString() + "',");;
           counter++;
        }

答案 5 :(得分:0)

string text = File.ReadAllText(&#34; C:\ Users \ person \ Desktop \ old.sql&#34;);             System.Text.StringBuilder strBuilder = new StringBuilder();

        int i = 0;

        var theSplotStr = text.Split('\n');

        foreach (var item in theSplotStr)
        {
            System.Console.WriteLine(item);
            string revisedString = item.Replace("''", "'" + ++i + "'");
            strBuilder.Append(revisedString+"\n");

        }

        File.WriteAllText("C:\\Users\\person\\Desktop\\new.sql", strBuilder.ToString());

答案 6 :(得分:0)

这是一把锤子,可以将拇指针推到板子上......

如果您感兴趣,可以通过并行执行此操作。启动一个任务来读取旧文件中的行,多个处理器任务以清理读取器任务读取的行,以及一个编写器任务将结果写回磁盘。

在我的8核机器上,我可以在不到3秒的时间内使用~100%CPU处理124MB文件。

下面附有完整注释的代码。

using System;
using System.Collections.Concurrent;
using System.IO;
using System.Threading.Tasks;

namespace ConsoleApplication
{
    public static class Test
    {
        //The paths to read and write
        const string OldFilePath = @"C:\Users\Donavon\Desktop\old.sql";
        const string NewFilePath = @"C:\Users\Donavon\Desktop\new.sql";

        //The maximum number of lines we can read for parallel processing
        //given the memory restrictions etc. Please set this to a number 
        //that is optimum for you.
        static readonly int ExpectedMaxLines = (int)Math.Pow(2, 10);

        //The data structures to hold the old and new lines
        private static readonly BlockingCollection<string> DirtyLines = new BlockingCollection<string>(ExpectedMaxLines);
        private static readonly BlockingCollection<string> CleanLines = new BlockingCollection<string>(ExpectedMaxLines);

        //A common factory. Since all tasks are long running, this is enough.
        private static readonly TaskFactory TaskFactory = new TaskFactory(TaskCreationOptions.LongRunning, TaskContinuationOptions.None);

        public static void Main()
        {
            //Need to start one reader task which will read one line at a time and
            //put that line in the BlockingCollection for parallel processing.

            BeginReader();

            BeginParallelProcessing();

            //We have started 1 reader task and multiple processor tasks
            //Now we need to start a writer task that will write the cleaned lines to disk
            var finalTask = BeginWriter();

            //Since writer task is the task which will signify the end of the entire 
            //exercise of reading, processing and writing, we will wait till the 
            //writer task has finished too.
            Task.WaitAll(new[] {finalTask});

            Console.WriteLine("All text lines cleaned and written to disk.");
        }

        private static void BeginReader()
        {
            TaskFactory.StartNew(() =>
            {
                Console.WriteLine("Reader task initiated.");
                using (var reader = new StreamReader(OldFilePath))
                {
                    string line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        DirtyLines.TryAdd(line);
                    }
                    DirtyLines.CompleteAdding();
                }
            });
        }

        private static void BeginParallelProcessing()
        {
            //Starting as many processor tasks as there are number of processors available
            //on this machine. These tasks will return when there are no more lines to process

            //Globally defined id, and a lock, for adding in the required lines.
            var globalId = 1;
            var idLock = new object();

            for (var taskIndex = 0; taskIndex < Environment.ProcessorCount; taskIndex++)
            {
                TaskFactory.StartNew(() =>
                {
                    while (!DirtyLines.IsCompleted)
                    {
                        string line, updatedLine;
                        if (!DirtyLines.TryTake(out line)) continue;
                        if (line.Contains("(''"))
                        {
                            int nextGlobalId;
                            lock (idLock)
                            {
                                nextGlobalId = globalId++;
                            }
                            updatedLine = line.Replace("('',", "('" + nextGlobalId + "',");
                        }
                        else
                        {
                            updatedLine = line;
                        }
                        CleanLines.Add(updatedLine);
                    }
                    //Adding a delay of 10 seconds to allow all processing tasks to finish
                    Task.Delay(10*1000);
                    if (!CleanLines.IsAddingCompleted)
                    {
                        CleanLines.CompleteAdding();
                    }
                });
            }
        }

        private static Task BeginWriter()
        {
            var finalTask = TaskFactory.StartNew(() =>
            {
                Console.WriteLine("Writer task initiated.");
                using (var writer = new StreamWriter(NewFilePath))
                {
                    while (!CleanLines.IsCompleted)
                    {
                        string cleanLine;
                        if (!CleanLines.TryTake(out cleanLine)) continue;
                        writer.WriteLine(cleanLine);
                    }
                }
            });
            return finalTask;
        }
    }
}

答案 7 :(得分:-1)

// Read file in by line (give us an array to work with)
var file = File.ReadAllLines("old.sql");

// Write the lines back (after we've modified it through LINQ)
File.WriteAllLines("new.sql", file.Select((line,index) => {
  // Use the overload of `.Select()` which includes the index

  // Simple string replace at this point, inserting our index.
  return line.Replace("('',", String.Format("('{0}',", index));
}));

答案 8 :(得分:-1)

string text = File.ReadAllText("old.sql");
text = text.Replace("some text", "new value");
File.WriteAllText("old.sql", text);