【发布时间】:2020-05-11 09:59:17
【问题描述】:
如果它以数组中的任何字符串开头,我正在尝试打印文本文件中的一行。
这是我的代码的 sn-p:
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"
}
但在我的情况下,我使用数组变量而不是字符串来选择内容,所以我被这部分难住了,因为它不起作用。它现在将打印任何内容。
更新: 感谢西奥的回答!这是我的代码基于 Theo 的答案供参考
array = "test:", "test1:"
$regex = '^({0})' -f (($array |ForEach-Object { [regex]::Escape($_) }) -join '|')
Loop here:
if($currentline -match $regex) {
Write-Output "Currentline: $currentline"
}
【问题讨论】:
标签: windows powershell select-string