在c#中,为每个由分割返回的项目搜索文本行
本文关键字:返回 项目 搜索 文本 分割 | 更新日期: 2023-09-27 17:49:18
我正在尝试阅读我的apache日志并使用它做一些处理。我使用一个字符串分割函数,其中包含以这种方式引用我的日志行。我想去掉这些线。下面的代码显示了我得到的。它只删除了"127.0.0.1",但删除了所有"192.168.1"。
如何删除每个分割字符串?
public void GetTheLog()
{
string path = "c:''program files''Zend''apache2''logs''access.log";
string path2 = @"access.log";
int pos;
bool goodline = true;
string skipIPs = "127.0.0.1;192.168.1.100;192.168.1.101;192.168.1.106;67.240.13.70";
char[] splitchar = { ';' };
string[] wordarray = skipIPs.Split(splitchar);
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
StreamReader reader = new StreamReader(fs);
TextWriter tw = new StreamWriter(path2);
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
// initialize goodline for each line of reader result
goodline = true;
for (j = 0; j < wordarray.Length; j++)
{
pos = -10;
srch = wordarray[j];
ln = line.Substring(0,srch.Length);
pos = ln.IndexOf(srch);
if (pos >= 0) goodline = false;
}
if (goodline == true)
{
tw.WriteLine(line);
listBox2.Items.Add(line);
}
}
// Clean up
reader.Close();
fs.Close();
listBox1.Items.Add(path2);
tw.Close();
}
var logPath = @"c:'program files'Zend'apache2'logs'access.log";
var skipIPs = "127.0.0.1;192.168.1.100;192.168.1.101;192.168.1.106;67.240.13.70";
var filters = skipIPs.Split(';');
var goodlines = File.ReadLines(logPath)
.Where(line => !filters.Any(f => line.Contains(f)));
那么你可以
File.WriteAllLines(@"access.log", goodlines);
看起来就像你把这些行放到了一个列表框
listBox2.Items.AddRange(goodlines.Select(line=> new ListItem(line)).ToArray());
同样,因为你的skipIPs
只是一个静态字符串,你可以稍微重构一下,只做
var filters = new []{"127.0.0.1","192.168.1.100","192.168.1.101",...};
arrrrrr没有得到你想要的…
好的,让我试一下,如果你想从当前文件中删除所有存在于你的skiip中的ip。
则可以简单地使用....
if(ln==srch)
{
goodline = false;
}
代替
pos = ln.IndexOf(srch);
if (pos >= 0) goodline = false;
在for循环中。
希望它能帮助你…:)