0

What is the best short one-liner in PowerShell to use as a grep alternative?

I wanted to share with you this short one-liner syntax for PowerShell version of grep, which perhaps is relatively little known.

6
  • 4
    Thanks for sharing! Can you edit the "question" part to make it fit better in this platform? For example, the title could be "How can I do X in PowerShell". Commented Apr 3, 2020 at 12:35
  • 1
    Have to agree with @Tom here. This is not a question on its own. Commented Apr 3, 2020 at 12:50
  • Hey @TomFenech, thanks for the suggestion! I do not quite understand how the title "How can I do X in PowerShell" would make it seem as not a question since there is no option in StackOverflow question forms to differentiate questions vs. "solutions" as well. Commented Apr 3, 2020 at 14:56
  • The point is that is should be written in a Question/Answer format. That is, your Question should be "how can I do X?" and your Answer should be "here is how you do it". Commented Apr 3, 2020 at 17:37
  • This is covered in the Help Center here stackoverflow.com/help/self-answer Commented Apr 3, 2020 at 17:38

1 Answer 1

2

# In Bash, one could write, for example:

grep -Po '^\w+ \w+' myfile

to extract the first two words from a given file.

# This can be translated to PowerShell in the following syntax:

(sls '^\w+ \w+' myfile).Matches.Value

where sls is the alias for Select-String. See: Get-Alias -Definition Select-String.

Another option:

(cat myfile) -match '^\w+ \w+'; $Matches.0

However, this one is already somewhat complex; and the first part outputs additional True/False, which you may want to discard.

Sign up to request clarification or add additional context in comments.

5 Comments

Note there is nothing specific to bash about your invocation of grep.
Might also note the alias cat is short for Get-Content.
Also note that if myfile contains more than 1 line, the -match solution, won't work - unless you add the -Raw switch to cat (Get-Content) in order to read the whole file as a single string.
I didn't know about grep's -o option to only output the match. In powershell 7, select-string highlights the match.
@chepner, yes, you are right! Can you suggest what to write instead?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.