我有一个.txt文件(日志)跟踪几行客户端的IP地址,格式类似于这个:
Line1 - Client IP [192.168.0.1] Other data Line2 - Client IP [192.168.0.2] Other data Line3 - Client IP [192.168.0.3] Other data Line4 - Client IP [192.168.0.2] Other data Line5 - Client IP [192.168.0.1] Other data ...
我需要创build脚本:
对于前面的例子,结果文件将是:
192.168.0.1 192.168.0.2 192.168.0.3
我在Windows操作系统上,但是我可以使用像Cygwin或Unix Tools (在Windows下提供类似于Unix的命令,如grep,sort等)的工具。
没有脚本的解决scheme也可以。
在此先感谢您的帮助。
在PowerShell中:
详细的方式 –
$regex = '(?<IPAddress>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' get-content log.txt | where-object {if ($_ -match $regex){$matches.ipaddress}} | group-object -noelement
更短的版本
gc log.txt | % {if ($_ -match $regex){$matches.ipaddress}} | group -n
这是一个简短的sed脚本,提取方括号之间的部分,然后sort -u
删除重复:
sed -e 's/^.*\[\(.*\)\].*$/\1/g' < inputfile | sort -u
cat yourfile.txt | sed 's/*\[//g' | sed 's/\]*//g' | sort | uniq > newfile.txt
括号内的转义可能是不必要的。 我不记得了 这些工具应该都可以在Cygwin上使用。
要简明扼要地打败sed脚本是相当困难的。 好的,可读性是个问题
您可以使用Scripting.FileSystemObject进行文件访问,使用VBScript的正则表达式和Dictionary对象,在VBScript中执行一个更为详细的,也许更可读的版本,如下所示。
Option Explicit Dim oFSO Dim oRgx Dim oMatch Dim oMatches Dim oStream Dim sLine Dim oDict Dim sIP Dim aKeys Dim sKey Set oFSO = CreateObject( "Scripting.FileSystemObject" ) Set oDict = CreateObject( "Scripting.Dictionary" ) Set oStream = oFSO.OpenTextFile( "log.txt", 1, False ) Set oRgx = new regexp oRgx.Pattern = "\[(.+?)\]" oRgx.Global = True Do While Not oStream.AtEndOfStream sLine = oStream.ReadLine Set oMatches = oRgx.Execute(sLine) For Each omatch in omatches sIP = oMatch.SubMatches(0) If Not oDict.Exists( sIP ) Then oDict.Add sIp,1 End If Next Loop aKeys = oDict.Keys For Each sKey in aKeys wscript.echo sKey Next
如果你可以使用Cygwin,那么就没有必要担心Windows脚本解决方案了。