如何在文本文件中逐行读取和替换字符串? [英] How can I read and replace Strings line by line in a Text File?
问题描述
我有一个读取此内容的文本文件:
I have a text file that reads this:
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,就像这样:
Notice for each line the first key is ''. For each line, I want to find that '', and replace it with a number (starting with 1), then add 1 to it as it goes to the next line, Like so:
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');
我已经尝试了几个小时,但是失败了.
I've been trying to do this for a couple of hours but I'm failing.
这就是我一直在想的(我知道这很不正确,但是我在C#中并不那么精明,所以也许你们中的一个可以帮助我提出正确的代码):
Here is what I've been thinking of (I know this is far from right, but I'm not that savvy in c#, so maybe one of you can help me come up with the right code):
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);
感谢您的帮助,非常感谢
Thanks for any help, It's greatly appreciated
推荐答案
您可以逐行阅读以下行:
You can read the lines in individually:
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);
这篇关于如何在文本文件中逐行读取和替换字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!