在文件中查找内容并替换所有行
Find content in file and replace all the line
我有一个包含如下内容的文件:
Elsa 12 15
Charlie 3 60
Mattew 4 0
我需要找到以名称开头的字符串,然后用更改后的值替换所有行。我不知道搜索前的值。
因此,例如我知道,我需要将 Mattew +2 添加到他的第一个值并将 +4 添加到第二个值,然后文件将如下所示:
Elsa 12 15
Charlie 3 60
Mattew 6 4
谢谢。
您可以使用此代码将文件读入 Line class (name,firtvalue,secondValue) List ,使用它,然后再次写入文件
列表行 = new List();
contentFile.Split("\n").ToList().ForEach(line =>
{
string[] Values = line.Split(" ").ToArray();
Lines.Add(new Line { Name = Values[0], FirstValue = int.Parse(Values[1]), SecondValue = int.Parse(Values[2]) });
});
您可以使用 for
循环遍历文件的每一行,并使用 string.StartsWith()
方法找到需要的行。然后,如果找到需要的行 - 只需使用提供的 nameToFind
和新的整数值 newValue1
和 newValue2
重写它,将它们与 string.Join()
和 " "
空格分隔符组合.
例如,如果您想为行中的两个数字设置新值。
static void EditValues(string nameToFind, int newValue1, int newValue2)
{
string file = @"S:\File.txt";
if (File.Exists(file))
{
string[] lines = File.ReadAllLines(file);
for (int i = 0; i < lines.Length; i++)
if (lines[i].StartsWith(nameToFind))
{
// Just rewrite line with same name but new values
lines[i] = string.Join(" ", nameToFind, newValue1, newValue2);
// Optionally, if there is no more values to edit - you can break loop immediately
break;
}
// Save (write) lines array back to file.
File.WriteAllLines(file, lines);
}
}
简化版本,创始索引为 Array.FindIndex
。请注意,如果文件中的“Mattew”很少 - 在这种情况下只会首先编辑。
static void EditValues(string nameToFind, int newValue1, int newValue2)
{
string[] lines = File.ReadAllLines("File.txt");
int index = Array.FindIndex(lines, line => line.StartsWith(nameToFind));
lines[index] = string.Join(" ", nameToFind, newValue1, newValue2);
File.WriteAllLines("File.txt", lines);
}
如果你只需要设置一行中的两个数字中的一个,你可以使用某种bool
标志(下面例子中的editFirstNumber
)来定义行中的第一个或第二个数字应该是编辑。
要获得这两个数字,您可以使用 string.Split()
方法通过 " "
空格分隔符拆分行。
仅编辑两个数字之一的示例:
static void EditValue(string nameToFind, int newValue, bool editFirstNumber)
{
string file = @"S:\File.txt";
if (File.Exists(file))
{
string[] lines = File.ReadAllLines(file);
for (int i = 0; i < lines.Length; i++)
if (lines[i].StartsWith(nameToFind))
{
string[] lineValues = lines[i].Split(new char[] { ' ' }, 3, StringSplitOptions.None);
// Parse numbers from line
int.TryParse(lineValues[1], out int number1); // First number
int.TryParse(lineValues[2], out int number2); // Second number
// By boolean flag you can manipulate which one of two numbers to edit
if (editFirstNumber)
number1 = newValue;
else
number2 = newValue;
lines[i] = string.Join(" ", nameToFind, number1, number2);
// Optionally, if there is no more values to edit - you can break loop immediatly
break;
}
File.WriteAllLines(file, lines);
}
}
然后您可以调用 EditValues("Mattew", 6, 4);
,其中指定您要查找的名称以及第一个和第二个整数的新值。或者调用 EditValue("Mattew", 6, true);
仅编辑行中的第一个数字,调用 EditValues("Mattew", 4, false);
编辑行中的第二个数字。
如果你不能确定每一行都匹配“String Number1 Number2”scheme,你可以在解析之前添加一些检查到int
(例如!string.IsNullOrEmpty(lineValues[1])
)或者使用int.TryParse(lineValues[1], out int currentValue1)
.
您可以使用此功能查找和替换文件中的行
public static bool lineChanger(string fileName, string name, int first_num, int sec_num)
{
//check for exist file
if (!File.Exists(fileName))
return false;
//find
var lines = File.ReadAllLines(fileName).ToList();
int index = lines.FindIndex(x => x.Substring(0, x.IndexOf(" ")).ToLower() == name.ToLower());
if (index == -1)
return false;
//edit line
var record = lines[index].Split(" ");
lines[index] = $"{record[0]} {Convert.ToInt32(record[1]) + first_num} {Convert.ToInt32(record[2]) + sec_num}";
File.WriteAllLines(fileName, lines);
return true;
}
我有一个包含如下内容的文件:
Elsa 12 15
Charlie 3 60
Mattew 4 0
我需要找到以名称开头的字符串,然后用更改后的值替换所有行。我不知道搜索前的值。
因此,例如我知道,我需要将 Mattew +2 添加到他的第一个值并将 +4 添加到第二个值,然后文件将如下所示:
Elsa 12 15
Charlie 3 60
Mattew 6 4
谢谢。
您可以使用此代码将文件读入 Line class (name,firtvalue,secondValue) List ,使用它,然后再次写入文件
列表行 = new List();
contentFile.Split("\n").ToList().ForEach(line =>
{
string[] Values = line.Split(" ").ToArray();
Lines.Add(new Line { Name = Values[0], FirstValue = int.Parse(Values[1]), SecondValue = int.Parse(Values[2]) });
});
您可以使用 for
循环遍历文件的每一行,并使用 string.StartsWith()
方法找到需要的行。然后,如果找到需要的行 - 只需使用提供的 nameToFind
和新的整数值 newValue1
和 newValue2
重写它,将它们与 string.Join()
和 " "
空格分隔符组合.
例如,如果您想为行中的两个数字设置新值。
static void EditValues(string nameToFind, int newValue1, int newValue2)
{
string file = @"S:\File.txt";
if (File.Exists(file))
{
string[] lines = File.ReadAllLines(file);
for (int i = 0; i < lines.Length; i++)
if (lines[i].StartsWith(nameToFind))
{
// Just rewrite line with same name but new values
lines[i] = string.Join(" ", nameToFind, newValue1, newValue2);
// Optionally, if there is no more values to edit - you can break loop immediately
break;
}
// Save (write) lines array back to file.
File.WriteAllLines(file, lines);
}
}
简化版本,创始索引为 Array.FindIndex
。请注意,如果文件中的“Mattew”很少 - 在这种情况下只会首先编辑。
static void EditValues(string nameToFind, int newValue1, int newValue2)
{
string[] lines = File.ReadAllLines("File.txt");
int index = Array.FindIndex(lines, line => line.StartsWith(nameToFind));
lines[index] = string.Join(" ", nameToFind, newValue1, newValue2);
File.WriteAllLines("File.txt", lines);
}
如果你只需要设置一行中的两个数字中的一个,你可以使用某种bool
标志(下面例子中的editFirstNumber
)来定义行中的第一个或第二个数字应该是编辑。
要获得这两个数字,您可以使用 string.Split()
方法通过 " "
空格分隔符拆分行。
仅编辑两个数字之一的示例:
static void EditValue(string nameToFind, int newValue, bool editFirstNumber)
{
string file = @"S:\File.txt";
if (File.Exists(file))
{
string[] lines = File.ReadAllLines(file);
for (int i = 0; i < lines.Length; i++)
if (lines[i].StartsWith(nameToFind))
{
string[] lineValues = lines[i].Split(new char[] { ' ' }, 3, StringSplitOptions.None);
// Parse numbers from line
int.TryParse(lineValues[1], out int number1); // First number
int.TryParse(lineValues[2], out int number2); // Second number
// By boolean flag you can manipulate which one of two numbers to edit
if (editFirstNumber)
number1 = newValue;
else
number2 = newValue;
lines[i] = string.Join(" ", nameToFind, number1, number2);
// Optionally, if there is no more values to edit - you can break loop immediatly
break;
}
File.WriteAllLines(file, lines);
}
}
然后您可以调用 EditValues("Mattew", 6, 4);
,其中指定您要查找的名称以及第一个和第二个整数的新值。或者调用 EditValue("Mattew", 6, true);
仅编辑行中的第一个数字,调用 EditValues("Mattew", 4, false);
编辑行中的第二个数字。
如果你不能确定每一行都匹配“String Number1 Number2”scheme,你可以在解析之前添加一些检查到int
(例如!string.IsNullOrEmpty(lineValues[1])
)或者使用int.TryParse(lineValues[1], out int currentValue1)
.
您可以使用此功能查找和替换文件中的行
public static bool lineChanger(string fileName, string name, int first_num, int sec_num)
{
//check for exist file
if (!File.Exists(fileName))
return false;
//find
var lines = File.ReadAllLines(fileName).ToList();
int index = lines.FindIndex(x => x.Substring(0, x.IndexOf(" ")).ToLower() == name.ToLower());
if (index == -1)
return false;
//edit line
var record = lines[index].Split(" ");
lines[index] = $"{record[0]} {Convert.ToInt32(record[1]) + first_num} {Convert.ToInt32(record[2]) + sec_num}";
File.WriteAllLines(fileName, lines);
return true;
}