计算字符串在windows中的文件中出现的次数

计算字符串在windows中的文件中出现的次数,windows,cmd,find,findstr,Windows,Cmd,Find,Findstr,我尝试使用下面的命令来计算所述字符串在一个大文件中出现的次数。(几个gig),但它只返回字符串出现的行数。这对我来说是有问题的,因为字符串每行出现多次 是否要计算字符串在CMD文件中出现的次数,或者这需要批处理文件 find /c "findthis9=""7""" *.xml > results.txt 我认为这是不可能的。如果您使用的是更高版本的windows,则可以从命令行调用powershell: powershell -Command "&{(Get-Content c

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

是否要计算字符串在CMD文件中出现的次数,或者这需要批处理文件

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

我认为这是不可能的。如果您使用的是更高版本的windows,则可以从命令行调用powershell:

powershell -Command "&{(Get-Content c:\test.xml) | Foreach-Object {([regex]::matches( $_, 'findthis9=\"7\"'))} | Measure-Object | select -expand Count}
只是澄清一下:除了可以直接从cmd运行之外,它还提供文件test.xml中的字符串findthis9=“7”的编号


对于文件中的每一行,匹配findthis9=“7”,测量(计数)结果,仅显示实际出现的次数。

如果您使用的是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
}

如果您有一个实用程序,可以在每次搜索字符串出现之前和之后插入换行符,那么这可以在批处理(或命令行)中轻松完成。这样做很容易。REPL.BAT是纯脚本,从XP开始将在任何现代Windows机器上本机运行。它对stdin执行正则表达式搜索/替换,并将结果写入stdout

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