Reputation: 635
I am trying to search two strings in any two consecutive lines and need help.
Two search strings are "Airport"
and "Rate"
and sample Input file is described below :
Content of Input file :
1. Airport
2. Rate
3. Some text
4. Some more text
5. Airport
6. Some text
Desired Output :
1. Airport
2. Rate
P.S. Airport
keyword in 5.
is not in desired output since 4.
and 6.
doesn't have Rate
keyword.
This is how I have get it so far :
PS> get-content "c:\Inputfile.txt" | select-string "Airport" -context 1 | s
elect-string "Rate" > c:\airportrate.txt
Thanks.
Upvotes: 2
Views: 4911
Reputation: 126752
Read the file content in chunks of two lines, cast each chunk to a string and test if it matches your criteria:
PS> Get-Content .\lines.txt -ReadCount 2 | Where-Object {"$_" -match 'Airport.*rate' }
1. Airport
2. Rate
Upvotes: 1
Reputation: 68273
Using V3:
$Text = Get-Content "c:\Inputfile.txt" -Raw
[regex]$regex = '(?m)(^\d+\.\sAirport.*?\n\d+\.\sRate.*?)'
$regex.Matches($Text).value
From get-help get-content (V3)
-Raw Ignores newline characters and returns the entire contents of a file in one string. By default, the contents of a file is returned as a array of strings that is delimited by the newline character.
Raw is a dynamic parameter that the FileSystem provider adds to the Get-Content cmdlet. This parameter works only in file system drives.
This parameter is introduced in Windows PowerShell 3.0.
Upvotes: 2
Reputation: 13877
Try something like this, I've tested this on your input and got the correct output.
$reader = [System.IO.File]::OpenText("c:\Inputfile.txt")
$prevLine = ""
try {
for(;;) {
$line = $reader.ReadLine()
if ($prevLine -ne "")
{
if ($line -Match "Rate")
{
if ($prevLine -Match "Airport")
{
$prevLine
$line
}
}
}
$prevLine = $line
}
}
finally {
$reader.Close()
}
Credit due: https://stackoverflow.com/a/4192419/770270
Upvotes: 1