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)
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)
3 Answers
Reset to default 4You could follow it up with a [^#]
, so:
^#
starts with#
[^#]
and is not followed by a#
See: https://regex101/r/YawMDO/1.
@'
# cat
######## foo
### bar
#################### fish
# dog
##### test
'@ -split '\r?\n' | Select-String '^#[^#]'
You could also use a negative lookahead: ^#(?!#)
, see https://regex101/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,}'
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
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.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745162803a4614469.html
# # dog
? Or# dog #
? – dawg Commented Feb 21 at 18:18