Often you may want to use PowerShell to print N lines after a specific matching pattern in a file.
You can use the following syntax to do so:
Select-String "Mavericks" teams.txt -context 0,3
This particular example looks for the pattern “Mavericks” in the file named teams.txt and prints the line itself that contains the pattern along with the 3 lines after it.
Note that we use the Select-String cmdlet to first select the line that contains the pattern from the file.
We then use the -context parameter to specify how many lines before (0) and after (3) the matched line to print as well.
The following example shows how to use this syntax in practice.
Example: How to Print N Lines After Matching Pattern in PowerShell
Suppose we have a text file in our current directory named teams.txt that contains information about various basketball teams.
We can use the Get-Content cmdlet to view the contents of this file:

Suppose that we would like to find the line that contains the string “Mavericks” and then print this line along with the 3 lines after it.
We can use the following syntax to do so:
Select-String "Mavericks" teams.txt -context 0,3
The following screenshot shows how to use this syntax in practice:

Notice that the line that contains “Mavericks” is printed along with the 3 lines after it in the file.
Note that if you wanted to print the matching line along with the 3 lines before it then you could use the following syntax instead:
Select-String "Mavericks" teams.txt -context 3,0
This will print the line that contains “Mavericks” along with the 3 lines before it in the file.
Note: You can find the complete documentation for the Select-String cmdlet along with the -context parameter in PowerShell here.
Related Tutorials
The following tutorials explain how to perform other common tasks in PowerShell:
PowerShell: How to Insert Line After Matching Pattern
PowerShell: How to Use Select-String and Only Return First Match
PowerShell: How to Count Number of Lines in File
