Windows下的“Unix shell” - 类似脚本

时间:2008-10-08 18:23:27

标签: windows unix shell scripting

我需要shell脚本大师的帮助。

我有一个.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
...

我需要创建以下脚本:

  • 从此文件中提取IP地址
  • 对IP地址进行分组(仅报告一次相同的IP地址)
  • 输出包含结果IP地址的文件

对于上一个示例,生成的文件将是:

192.168.0.1
192.168.0.2
192.168.0.3

我在Windows操作系统上,但我可以使用CygwinUnix Tools等工具(在Windows下提供类似Unix的命令,如grep,sort等)。

没有脚本的解决方案也可能很好。

提前感谢您的帮助。

5 个答案:

答案 0 :(得分:6)

在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

答案 1 :(得分:4)

这是一个简短的sed脚本,它提取方括号之间的部分,然后sort -u删除重复项:

sed -e 's/^.*\[\(.*\)\].*$/\1/g' < inputfile | sort -u

答案 2 :(得分:2)

 cat yourfile.txt | sed 's/*\[//g' | sed 's/\]*//g' | sort | uniq > newfile.txt

括号可能不需要逃脱。我不记得了。这些工具应该都可以在Cygwin上使用。

答案 3 :(得分:1)

为了简洁起见,很难击败那些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

答案 4 :(得分:0)

如果您可以使用Cygwin,则无需担心Windows脚本解决方案。