[英]How do I check a string exist in a file using PowerShell?
我有一个第一个文本文件,看起来像这样: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"
}
您当前的方法存在许多问题。
# strings split into groups of two '12' 'AB' '34' # first string 'CD' ' 3' '4 ' # second string
当您使用-match
测试多个字符串时,您需要
.
)匹配,并且 $Compare = $FBString_Split | % {$Data_Split -match [regex]::Escape($_)}
if ($Compare -contains $true) {
Write-Host "Found"
} else {
Write-Host "Not Found"
}
为了找到一种更通用的解决方案,以找出一个字符串的N个字符的任何子字符串是否也是另一个字符串的子字符串,您可以改为执行以下操作:
$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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.