View Single Post
Old 02-16-2008   #3 (permalink)
Kiron


 
 

Re: The next line in a text file

When retrieving a file's content, Get-Content returns a String object for each line in the file, if there is more than one line you get an array of String objects. When the number of elements expected is unknown --could be zero, one or more-- and you want to ensure an array, enclose the command in an array subexpression '@(...)'
Select-String returns MatchInfo objects or a Boolean value. You can retrieve just one property from the MatchInfo objects --in your case the LineNumber property-- and get an array of these values. The MatchInfo object's LineNumber values are origin-one, i.e. the first line of the file, this is important to remember because PowerShell's array is origin-zero.
If you get the LineNumber value of the last line that matched a pattern in the html file and would like to rerrieve the _same_ line from the array of Strings returned by Get-Content, you would have to subtract 1 from it to use it as the index. Since you want to retrieve the _next_ line just use the LineNumber value you get from Select-String as the index for the String object array.
PowerShell's array notation allows negative index, i.e. -1 is the last element, -2 the next to last and so on.

$htmlFile = 'd:\work\test.html'
$pattern = "ABCDEF"

# last match's line number
$c = @(select-string $pattern $htmlFile | % {$_.lineNumber})[-1]
# next line
@(gc $htmlFile)[$c]

# or...
@(gc $htmlFile)[@(select-string $pattern $htmlFile | % {$_.lineNumber})[-1]]

--
Kiron
My System SpecsSystem Spec