[英]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.