[英]Print line of text file if it starts with any string in array
如果它以数组中的任何字符串开头,我正在尝试打印文本文件中的一行。
这是我的代码片段:
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"
}
但在我的情况下,我使用的是数组变量而不是字符串到 select 的内容,所以我在这部分被难住了,因为它不起作用。 它现在将打印任何内容。
更新:感谢西奥的回答! 这是我的代码基于 Theo 的答案供参考
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 { $_ }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.