【问题标题】:How to use regex with powershell to remove specific lines?如何使用正则表达式和 powershell 删除特定行?
【发布时间】:2021-01-14 17:37:16
【问题描述】:

如何删除下面匹配的行:

PS /home/nicholas/powershell/regex> 
PS /home/nicholas/powershell/regex> $doc = Get-Content ./foo.txt
PS /home/nicholas/powershell/regex> 
PS /home/nicholas/powershell/regex> $doc                        


a
b
c
d
e
f
g
hmmm i j k l m
n
o
p
q


PS /home/nicholas/powershell/regex> 
PS /home/nicholas/powershell/regex> $doc | Select-String 'h'

hmmm i j k l m

PS /home/nicholas/powershell/regex> 

这只是一个示例,但希望遍历 $doc 删除匹配的特定行。

这里,任何行带有“h”的行都会被删除。

换个角度看,返回所有其他不匹配的行

【问题讨论】:

  • 不需要正则表达式进行相同的比较。如果$doc 是一个数组,那么$doc -ne 'h i j k l m'
  • $doc 是一个文本文件
  • 还是文本文件内容?试试$doc -split '\r?\n' | where { !$_.contains("h") }
  • Select-String -NotMatch 'h'
  • $doc = @($doc) -notmatch 'h' 也可以

标签: string powershell read-eval-print-loop select-string


【解决方案1】:

感谢 cmets:

PS /home/nicholas/powershell/regex> 
PS /home/nicholas/powershell/regex> $doc | Select-String -notmatch 'h'



a
b
c
d
e
f
g
n
o
p
q



PS /home/nicholas/powershell/regex> 

似乎有效。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 2019-02-16
    • 2023-04-09
    • 2015-12-17
    • 2014-05-23
    • 1970-01-01
    相关资源
    最近更新 更多