Reputation: 199
So I have been searching a lot and couldn't find anything that wouldn't return me nothing.
I have a code with a variable and I have a file with a lot of lines on it. For example, I have the following file (things.txt):
Ketchup
Mustard
Pumpkin
Mustard
Ketchup
And what I want to take out is the line numbers of "Mustard". Here's the code I'm trying right now
$search="Mustard"
$linenumber=Get-Content things.txt | select-string $search -context 0,1
$linenumber.context
But it actually returns "". Everyone online was about using context but I only want to know the line number of every "Mustard" which are 2 and 4.
Thanks for your help!
Upvotes: 7
Views: 55273
Reputation: 3826
Let me give a practical example of usage.
Here is an example together with Docker logs. I have running a Docker container with container id starting with 42. I want to see why the Docker container fails at start. It tries to connect to Mongoose DB and container fails. I redirect the output and I use select-string to achieve this.
First I run this command :
docker logs 42 2>&1 | select-string -pattern "Error" | select LineNumber,Line
This then gives me both the LineNumber and the Line, so I can see where in the output I have the pattern with text "Error".
You can use this on similar streams such as strings and files that are string based in Powershell.
Upvotes: 0
Reputation: 231
For people who are searching for one liner, code is self explanatory.
Get-Content .\myTextFile.txt | Select-String -Pattern "IamSearching" | Select-Object LineNumber
Edit(April 2022):
OR
(Select-String .\myTextFile.txt -Pattern "IamSearching").LineNumber
Upvotes: 5
Reputation: 8442
Select-String
returns the line number for you. You're just looking at the wrong property. Change your code to:
$search="Mustard"
$linenumber= Get-Content thing.txt | select-string $search
$linenumber.LineNumber
Upvotes: 18