如果文本文件以数组中的任何字符串开头,则打印该行
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
我在 Whosebug 上看到了一些问题的解决方案:
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"
}
使用正则表达式 -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 { $_ }
}
我正在尝试打印文本文件中以数组中的任何字符串开头的一行。
这是我的代码片段:
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
我在 Whosebug 上看到了一些问题的解决方案:
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"
}
使用正则表达式 -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 { $_ }
}