ilRobby
ilRobby

Reputation: 113

powershell Regex - match only the strings that starts with one occurrence of special chars

I've a file that contains:

# cat
######## foo
### bar
#################### fish
# dog
##### test

with 'Get-Content file.txt | Select-String -Pattern "^#"' I match all those lines... How to get only the lines that starts with only one "#"? (the lines with cat and dog)

Upvotes: 3

Views: 82

Answers (3)

burnie
burnie

Reputation: 11

The simplest way to get # cat and # dog in the example is using -Pattern '^# '

Though, in this case it must be ensured that the line always starts with # followed by at least one whitespace. Lines with leading whitespaces and also strings directly adjacent after # without any whitespaces between will not match.

# cat
######## foo
### bar
#################### fish
# dog
##### test
   #     bird
      #monkey

For getting # cat, # dog, # bird and #monkey it's better to use:

Get-Content file.txt | Select-String -Pattern '^(\s*)#(?!#)'

The solution of using a negative lookahead (?!#) has already been mentioned.

^(\s*) describes that at the start of the line any whitespace characters in zero or more occurrence before # will match.

Upvotes: 0

Santiago Squarzon
Santiago Squarzon

Reputation: 60838

You could follow it up with a [^#], so:

  • ^# starts with #
  • [^#] and is not followed by a #

See: https://regex101.com/r/YawMDO/1.

@'
# cat
######## foo
### bar
#################### fish
# dog
##### test
'@ -split '\r?\n' | Select-String '^#[^#]'

You could also use a negative lookahead: ^#(?!#), see https://regex101.com/r/9YHjkB/1.

... | Select-String '^#(?!#)'

Yet another option could be to use Select-String -NotMatch with a pattern that matches a string starting with 2 or more #:

... | Select-String -NotMatch '^#{2,}'

Upvotes: 4

dawg
dawg

Reputation: 104082

For

# cat
# dog

(ie, starts with # with no other # in the line)

You could do ^#[^#]*$

Demo

If it is only the second character that matters, you could do ^#[^#].*

Demo

Upvotes: 0

Related Questions