代码之家  ›  专栏  ›  技术社区  ›  friol

Windows下的“unixshell”类脚本

  •  1
  • friol  · 技术社区  · 17 年前

    我有一个.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操作系统,但我可以使用以下工具 Cygwin Unix Tools (在Windows下提供类似Unix的命令,如grep、sort等)。

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

    提前感谢你的帮助。

    5 回复  |  直到 17 年前
        1
  •  6
  •   Steven Murawski    17 年前

    在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
    
        2
  •  4
  •   David Schmitt    17 年前

    sort -u 删除重复项:

    sed -e 's/^.*\[\(.*\)\].*$/\1/g' < inputfile | sort -u
    
        3
  •  2
  •   Robert Elwell    17 年前
     cat yourfile.txt | sed 's/*\[//g' | sed 's/\]*//g' | sort | uniq > newfile.txt
    

    应该

        4
  •  1
  •   bugmagnet    17 年前

    您可以在VBScript中使用Scripting.FileSystemObject进行文件访问,使用VBScript的正则表达式和Dictionary对象,创建更详细、更可读的版本,如下所示。

    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
    
        5
  •  0
  •   skiphoppy    16 年前

    如果您可以使用Cygwin,那么就不必担心Windows脚本解决方案。