Powershell命令检查PDF文件中随机2个单词之间的字符计数

zwghvu4y  于 2022-12-26  发布在  Shell
关注(0)|答案(1)|浏览(122)

我试图找出PowerShell命令来检查文件中2个随机单词之间的字符数。
下面的脚本给出了一个文件中的总字符数。但是,我正在寻找计数,我在文件中提到2个随机单词,并计算字符数:

dir -Include *.* -Recurse | % { 
  $_ | select name, 
    @{n="characters";e={get-content $_ | measure-object -character | select -expa characters }} , 
    @{n="words";     e={get-content $_ | measure-object -word      | select -expa words }} , 
    @{n="lines";     e={get-content $_ | measure-object -line      | select -expa lines }}
} | 
ft -AutoSize
krcsximq

krcsximq1#

下面是一个示例文件test.txt

hello world example
this is sample text

你可以尝试这样的方法:

$firstWord = "world"
$lastWord  = "sample"

# in keeping with your example:
@{n="charBetween";e={
  # Get raw content for a single string instead of per-line
  $text = Get-Content $_ -Raw

  # index of first and last words
  $i1 = $text.IndexOf($firstWord) + $firstWord.Length  
  $i2 = $text.IndexOf($lastWord) - 1

  # return -1 if one of the words was not found
  if ($i1,$i2 -eq -1) { return -1 }

  # output count each character between words
  else { $text[$i1..$i2].Count }
}}

# returns like this:

charBetween
-----------
18

请注意,Get-Content -Raw包含换行符,因此如果包含多行,则计数会稍高。

相关问题