powershell: how to remove first # in each row of t

2020-04-30 02:04发布

E.g. I've got a text file like this:

abc,#32432,he#llo
xyz,#989,wor#ld

I wish to change it to be:

abc,32432,he#llo
xyz,989,wor#ld

Just remove first "#" from each row. How to do that? Thanks.

2条回答
ゆ 、 Hurt°
2楼-- · 2020-04-30 02:43

To only change the first # in a string you could use a regular expression like this

"abc,#32432,he#llo" -replace '(.*?)#(.*$)', '${1}${2}'

Explanation as by Regexbuddy

# (.*?)#(.*$)
# 
# Options: Case insensitive; Exact spacing; Dot doesn't match line breaks; ^$ match at line breaks; Parentheses capture
# 
# Match the regex below and capture its match into backreference number 1 «(.*?)»
#    Match any single character that is NOT a line break character (line feed) «.*?»
#       Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
# Match the character “#” literally «#»
# Match the regex below and capture its match into backreference number 2 «(.*$)»
#    Match any single character that is NOT a line break character (line feed) «.*»
#       Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
#    Assert position at the end of a line (at the end of the string or before a line break character) (line feed) «$»
查看更多
Lonely孤独者°
3楼-- · 2020-04-30 02:46

You can use simple regex that replaces a hash that follows a section of non hashes with nothing, something like this:

Get-Content input_file.txt | % {$_ -replace '(?<=^[^#]+)#'} | Set-Content output_file.txt
查看更多
登录 后发表回答