My goal is to find the index of a line containing in substring in an array. And I would like to do this for multiple substrings.
The closest thing I could find would be to Loop through the array and test -match. This works fine when I explicitly put in the substring. But there are quite a few substrings I want to find so I tried to loop through an array:
[pre]
For ($j = 0; $j -lt $list.length; $j++) {
For ($i=0; $i -lt $file.length; $i++) {
$file[$i] -match ‘THH06121’ #this works just great
$file[$i] -match $list[$j] #this does not work - it just returns every single line as true
}
}
[/pre]
So $list[0] is THH06121, but it doesn’t seem to work. I’ve tried having quotes in the $list, I’ve tried having them in the body.
Hope you can help me! My end goal is to search for these substrings and replace the lines after them up to the next empty line.
I gave this a little test run just to see if it’d work, and it does seem to.
# mockup for a file with a few lines in it
$File = @( "hello", "THH06121", "bye", "nope" )
# List of stuff to find
$List = @( "no", "THH06121" )
for ($listIndex = 0; $listIndex -lt $list.Length; $listIndex++) {
for ($fileIndex = 0; $fileIndex -lt $file.Length; $fileIndex++) {
if ($file[$fileIndex] -match $list[$listIndex]) { $fileIndex }
}
}
The results are 3 and 1 which track with what I have going in as the input.
What’s actually in your list? You might need to escape the patterns you’re searching for depending on the characters they contain; -match uses regex, so if they contain characters considered “special” you’ll have to escape them. A good catch-all, if you know all the things you’re looking for are literal strings, is a nice easy [regex]::Escape($pattern)