【问题标题】:How do I check a string exist in a file using PowerShell?如何使用 PowerShell 检查文件中是否存在字符串?
【发布时间】:2019-03-05 07:47:31
【问题描述】:

我的第一个文本文件如下所示:12AB34.US。第二个文本文件是 CD 34 EF。 我想在第一个文本文件中查找我的第二个文本文件是否存在。

我尝试在第一个文本文件 (.US) 中最后剪切 3 个字符。然后我拆分为每 2 个字符(因为第二个文本文件由 2 个字符组成)。然后,我尝试了这段代码,它总是返回“未找到”。

$String = Get-Content "C:\Users\te2.txt"
$Data = Get-Content "C:\Users\Fixed.txt"
$Split = $Data -split '(..)'

$Cut = $String.Substring(0,6)

$String_Split = $Cut -split '(..)'
$String_Split

$Check= $String_Split | %{$_ -match $Split}
if ($Check-contains $true) {
    Write-Host "0"
} else {
     Write-Host "1"
}

【问题讨论】:

  • 这对我来说很不清楚.. text2 中唯一也在 text1 中的字符是数字34。这已经足以让你称之为“比赛”了吗?
  • 是的。但我不确定 text1 中是否存在另一个检查 text2 中数据的函数。 @Theo

标签: string powershell match powershell-3.0 contains


【解决方案1】:

您当前的方法存在许多问题。

  1. 2 字符组不对齐:
# 字符串分成两组 '12' 'AB' '34' # 第一个字符串 'CD' ' 3' '4 ' # 第二个字符串
  1. 当你用-match测试多个字符串时,你需要

    1. 转义输入字符串以避免匹配元字符(如.),以及
    2. 将集合放在运算符的左侧,模式放在右侧:

$Compare = $FBString_Split | % {$Data_Split -match [regex]::Escape($_)}
if ($Compare -contains $true) {
    Write-Host "Found"
} else {
     Write-Host "Not Found"
}

要找到一个更通用的解决方案来确定一个字符串的 N 个字符的 any 子字符串是否也是另一个字符串的子字符串,您可能可以这样做:

$a = '12AB34.US'
$b = 'CD 34 EF'

# we want to test all substrings of length 2
$n = 2

$possibleSubstrings = 0..($n - 1) | ForEach-Object {
    # grab substrings of length $n at every offset from 0 to $n
    $a.Substring($_) -split "($('.'*$n))" | Where-Object Length -eq $n |ForEach-Object {
        # escape the substring for later use with `-match`
        [regex]::Escape($_)
    }
} |Sort-Object -Unique

# We can construct a single regex pattern for all possible substrings:
$pattern = $possibleSubstrings -join '|'

# And finally we test if it matches
if($b -match $pattern){
    Write-Host "Found!"
}
else {
    Write-Host "Not found!"
}

这种方法会给你正确的答案,但在大输入时它会变得非常慢,此时你可能需要查看非基于正则表达式的策略,如 Boyer-Moore

【讨论】:

  • 它总是找到,即使我将 $b 更改为 : C34DEF 。但是我的期望 $b 在处理与 $a 比较时会分成每 2 个字符。
猜你喜欢
  • 1970-01-01
  • 2014-10-26
  • 1970-01-01
  • 2014-12-11
  • 2013-12-15
  • 2019-04-07
  • 2020-02-28
  • 2017-12-11
  • 2021-10-07
相关资源
最近更新 更多