admin管理员组

文章数量:1414933

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)

Share Improve this question asked Feb 21 at 17:52 ilRobbyilRobby 1131 gold badge2 silver badges10 bronze badges 1
  • What about # # dog? Or # dog #? – dawg Commented Feb 21 at 18:18
Add a comment  | 

3 Answers 3

Reset to default 4

You 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.

本文标签: powershell Regexmatch only the strings that starts with one occurrence of special charsStack Overflow