简体   繁体   中英

Print line of text file if it starts with any string in array

I am trying to print out a line in a text file if it starts with any of the string in the array.

Here is a snippet of my code:

array = "test:", "test1:"
    if($currentline | Select-String $array) {
        Write-Output "Currentline: $currentline"
    }

My code is able to print lines in the text file if it has any of the strings in the array variable. But I only want to print lines if it starts with the string in array variable.

Sample of text file:
abcd-test: 123123
test: 1232
shouldnotprint: 1232

Output: 
abcd-test: 123123
test: 1232

Expected output:
test: 1232  

I have seen some questions asked on stackoverflow with the solution:

array = "test:", "test1:"
    if($currentline | Select-String -Pattern "^test:") {
        Write-Output "Currentline: $currentline"
    }

But in my case I am using an array variable instead of a string to select the content so I am stumped at this portion because it would not work. It will just now print anything.

Update: Thanks Theo for your answer! This is my code based on Theo's answer for reference

array = "test:", "test1:" 
$regex = '^({0})' -f (($array |ForEach-Object { [regex]::Escape($_) }) -join '|') 
Loop here:
   if($currentline -match $regex) {
       Write-Output "Currentline: $currentline"
   }

Using the Regex -match operator should do what you want:

$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 }

Or, if the file to read is really huge, use a switch -Regex -File method like:

switch -Regex -File 'D:\Test\test.txt' {
    $regex { $_ }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM