[英]powershell in-place remove double quotes in text file where line starts with double quotes + some other text
仅当行以“https”开头时,我才需要删除文本文件中的双引号。 文件内容是这样的:
...
"bla, bla, bla"
"https://example.com"
"bar, bar, bar"
...
我必须匹配“ https://example.com ”,删除两个双引号,在其他行中保留双引号,而不是 set-content ......
我尝试了很多方法,但我被卡住了,因为我不知道如何处理正则表达式中的双引号,或者在“if”或“where”语句中声明过滤器,而不是替换文本......
最新尝试:
$TextFile = Get-Content "e:\file.txt"
foreach ($Line in $TextFile) {if ($Line.StartsWith('"https')) { $line.trim('"')} | Set-Content $TextFile
但不起作用...
我已经阅读了这篇文章和这篇文章,但我不明白如何让这些解决方案满足我的需求..
有人能帮助我吗?
使用-Raw
开关将文本文件作为单个字符串读取,然后进行正则表达式替换:
(Get-Content "e:\file.txt" -Raw) -replace '(\s*)"(https:[^"]+)"','$1$2'
如果需要用新内容覆盖文本文件,append
| Set-Content -Path "e:\file.txt" -Force
到上面。
Output:
... "bla, bla, bla" https://example.com "bar, bar, bar" ...
正则表达式详细信息:
( Match the regular expression below and capture its match into backreference number 1 \s Match a single character that is a “whitespace character” (spaces, tabs, line breaks, etc.) * Between zero and unlimited times, as many times as possible, giving back as needed (greedy) ) " Match the character “"” literally ( Match the regular expression below and capture its match into backreference number 2 https: Match the characters “https:” literally [^"] Match any character that is NOT a “"” + Between one and unlimited times, as many times as possible, giving back as needed (greedy) ) " Match the character “"” literally
要获取不带双引号的“https://”字符串:
$content = Get-Content PATH TO YOUR FILE
foreach( $line in $content ) {
if( $line -match "(`"https:\/\/)" ) {
$line -replace '"',''
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.