regexpowershell

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)


Solution

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

    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,}'