2014-09-19 78 views
0

我尝试使用下面的命令来计算所述字符串出现在大文件中的次数。 (几个演出),但它只返回字符串出现的行数。这对我来说是有问题的,因为字符串每行出现多次。计算字符串在窗口中出现在文件中的次数

反正有计算字符串出现在CMD文件中的次数还是需要批处理文件?

find /c "findthis9=""7""" *.xml > results.txt 

回答

0

我不认为这是可能的。如果你在以后的窗口,你可以从命令行调用的PowerShell:

powershell -Command "&{(Get-Content c:\test.xml) | Foreach-Object {([regex]::matches($_, 'findthis9=\"7\"'))} | Measure-Object | select -expand Count} 

只是澄清:除了是从CMD运行的直接,它也给你的字符串findthis9 =“7”的数量在文件test.xml。

对于文件中的每一行,匹配findthis9 =“7”,measure(count)结果,仅显示实际发生的次数。

0

如果您使用的是Windows XP或更高版本,则理论上可以使用Windows PowerShell。如果系统是Windows Vista,那么你一定可以。如果它确实是XP,那么你需要确保首先安装PowerShell。下面的代码:

# Windows PowerShell 
# All text following a '#' is a comment line, like the 'rem' keyword in cmd 
$file = Get-Content MyFile.xml # you can change this to *.xml if you wish 

# split the file variable on all instances of a space 
$file = $file.Split(" ") 

# declare the pattern 
$pattern = "findthis9=""7""" 
# declare a variable to use as a counter for each occurence 

for ($i = 0; $i -lt $file.GetUpperBound(""); $i++) 
{ 
    if ($file[$i] -match $pattern) 
    { 
     ++$counterVariable 
    } 
} 

return $counterVariable 

另外,如果你把这个变成一个功能,那么你可以通过文件做到这一点,因为你可以用它在文件中出现的次数返回的文件名。请看下图:

function Count-NumberOfStringInstances() 
{ 
    [CmdletBinding()] 

    # define the parameters 
    param (

    # system.string[] means array, and will allow you to enter a list of strings 
    [Parameter()] 
    [System.String[]]$FilePath, 

    [Parameter()] 
    [System.String]$TextPattern 
    ) 

    $counterVariable = 0 

    $files = Get-ChildItem -Path $FilePath 

     $file = Get-Content $FilePath # you can change this to *.xml if you wish 

     # split the file variable on all instances of a space 
     $file = $file.Split(" ") 

     # declare the pattern 
     # declare a variable to use as a counter for each occurence 

     for ($i = 0; $i -lt $file.GetUpperBound(""); $i++) 
     { 
      if ($file[$i] -match $TextPattern) 
      { 
       ++$counterVariable 
      } 
     } 

     # return the counter variable 

    return $counterVariable 
} 
1

这可以很容易地在批处理来完成(或命令行),如果你有一个实用工具,可以前后搜索字符串的每次出现后插入一个换行符。 REPL.BAT hybrid JScript/batch utility可以很容易地做到这一点。 REPL.BAT是纯粹的脚本,它可以从XP以后的任何现代Windows机器上本机运行。它在stdin上执行正则表达式搜索/替换并将结果写入标准输出。

<test.xml repl "(findthis9=\q7\q)" \n$1\n x | find /c "findthis9=""7""" 
相关问题