2014-09-19 74 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""" 
相關問題