Windows 如果文本文件的行以数组中的任何字符串开头,则打印该行
我试图打印文本文件中的一行,如果它以数组中的任何字符串开头 以下是我的代码片段:Windows 如果文本文件的行以数组中的任何字符串开头,则打印该行,windows,powershell,select-string,Windows,Powershell,Select String,我试图打印文本文件中的一行,如果它以数组中的任何字符串开头 以下是我的代码片段: array = "test:", "test1:" if($currentline | Select-String $array) { Write-Output "Currentline: $currentline" } 如果在数组变量中有任何字符串,我的代码可以打印文本文件中的行。但我只想在数组变量中以字符串开头时打印行 Sample of text file: abcd-tes
array = "test:", "test1:"
if($currentline | Select-String $array) {
Write-Output "Currentline: $currentline"
}
如果在数组变量中有任何字符串,我的代码可以打印文本文件中的行。但我只想在数组变量中以字符串开头时打印行
Sample of text file:
abcd-test: 123123
test: 1232
shouldnotprint: 1232
Output:
abcd-test: 123123
test: 1232
Expected output:
test: 1232
我看到了有关stackoverflow的一些问题以及解决方案:
array = "test:", "test1:"
if($currentline | Select-String -Pattern "^test:") {
Write-Output "Currentline: $currentline"
}
但在我的例子中,我使用数组变量而不是字符串来选择内容,因此我在这一部分遇到了困难,因为它不起作用。它现在可以打印任何东西
更新:
谢谢西奥的回答!这是我根据西奥的答案编写的代码,仅供参考
array = "test:", "test1:"
$regex = '^({0})' -f (($array |ForEach-Object { [regex]::Escape($_) }) -join '|')
Loop here:
if($currentline -match $regex) {
Write-Output "Currentline: $currentline"
}
使用Regex
-match
操作符应该执行您想要的操作:
$array = "test:", "test1:"
# create a regex string from the array.
# make sure all the items in the array have their special characters escaped for Regex
$regex = '^({0})' -f (($array | ForEach-Object { [regex]::Escape($_) }) -join '|')
# $regex will now be '^(test:|test1:)'. The '^' anchors the strings to the beginning of the line
# read the file and let only lines through that match $regex
Get-Content -Path 'D:\Test\test.txt' | Where-Object { $_ -match $regex }
或者,如果要读取的文件非常大,请使用switch-Regex-file
方法,如:
switch -Regex -File 'D:\Test\test.txt' {
$regex { $_ }
}
嗨,提奥,谢谢你的回答。为了理解您的代码,它正在尝试循环遍历数组,以便我们可以转义特殊字符并附加一个“|”将每个项连接在一起。然后,该输出将存储在$regex中,我们将使用“where Object”将当前行与生成的regex语句匹配。我可以知道第3行的“-f”选项是什么意思吗?这是“[regex]::Escape($904;)”Powershell调用函数的等价物(在本例中是regex.Escape)?@pikachu
-f
是字符串格式运算符。看见是的,[Regex]::Escape()
正在调用.Net的System.Text.RegularExpressions.Regex.Escape()函数。严格来说,[Regex]
是一个类名,:
是静态成员运算符,Escape()
是成员函数。您可以将其称为[System.Text.RegularExpressions.Regex]::Escape()
。