Reputation: 113
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
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
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