下面的文本文件示例
text_file a
Text_ID“441124_aad0656_1234”
Text_FILE_NAME
我想只保留字符串“1234”的最后一个索引
StreamReader streamReader = new StreamReader(text);
string text2;
while ((text2 = streamReader.ReadLine()) != null)
{
num++;
string[] array3 = text2.Split(new char[0]);
if (array3[0] == "Text_ID")
{
string[] array4 = array3[1].Split(new char[] {'_'});
string value = "Text_ID" + " " + '"' + array4[1];
streamWriter.WriteLine(value);
}
else
{
streamWriter.WriteLine(text2);
}
}
答案 0 :(得分:0)
您可以使用File.ReadAllLines
将文件读入数组,然后在数组中搜索要更改的行,用新字符串替换该行,然后使用File.WriteAllLines
写入数组返回文件:
var filePath = @"f:\public\temp\temp.txt";
// The string to search for
var searchTxt = "Text_ID";
// Read all the lines of the file into an array
var fileLines = File.ReadAllLines(filePath);
// Loop through each line in the array
for(int i = 0; i < fileLines.Length; i++)
{
// Check if the line begins with our search term
if (fileLines[i].Trim().StartsWith(searchTxt, StringComparison.OrdinalIgnoreCase))
{
// Get the end of the line, after the last underscore
var lastPartOfLine = fileLines[i].Substring(fileLines[i].LastIndexOf("_") + 1);
// Combine our search string, a quote, and the end of the line
fileLines[i] = $"{searchTxt} \"{lastPartOfLine}";
// We found what we were looking for, so we can exit the for loop now
// Remove this line if you expect to find more than one match
break;
}
}
// Write the lines back to the file
File.WriteAllLines(filePath, fileLines);
如果您只想保存文件的最后四行,可以调用Skip
并传入数组的Length
减去要保留的行数。这会跳过您要保存的所有条目:
// Read all the lines of the file into an array
var fileLines = File.ReadAllLines(filePath);
// Take only the last 4 lines
fileLines = fileLines.Skip(fileLines.Length - 4).ToArray();
答案 1 :(得分:0)
尝试下面的代码,希望它适合你。
var startsWith = "Text_ID";
var allLines = File.ReadAllLines("a.txt").ToList();
allLines = allLines.Select(ln =>
{
if(ln.StartsWith(startsWith))
{
var finalValue = ln.Split(' ')[1].Trim('"').Split('_').Last();
//get update line
return string.Format("{0} \"{1}\"", startsWith, finalValue);
}
return ln;
}).ToList();
//Write back to file.
File.WriteAllLines("a.txt", allLines.ToArray());
代码执行前的内容。
Record 1
Text_ID "441124_aad0656_1234"
other content.
Record 2
Text_ID "Deepak_Sharma"
other content for line 2
执行后的文件内容。
Record 1
Text_ID "1234"
other content.
Record 2
Text_ID "Sharma"
other content for line 2