【问题标题】:How can I write the output of Select-String in powershell without the line numbers?如何在没有行号的情况下在 powershell 中编写 Select-String 的输出?
【发布时间】:2020-02-20 19:14:26
【问题描述】:

我正在使用 powershell 使用正则表达式过滤文本文件。为此,我使用以下命令: Select-String -Pattern "^[0-9]{2}[A-Z]{2}[a-z]{5}" -CaseSensitive rockyou.txt > filter.txt 然而,问题是,当将它们写入 filter.txt 时,它位于匹配的字符串之前,原始文件的名称后跟行号,例如:

rockyou.txt:12345:abcdefg

rockyou.txt:12345:abcdefg

rockyou.txt:12345:abcdefg

我怎样才能让它省略行号?

【问题讨论】:

  • 管它。类似Select-String -Pattern "^[0-9]{2}[A-Z]{2}[a-z]{5}" -CaseSensitive rockyou.txt | $_.split(":")[-1] | Out-File(filter.txt)
  • 匹配的字符串不会是 01ABcdefg 之类的吗?

标签: powershell select-string


【解决方案1】:

Select-String 为每个匹配输出一个对象,每个对象都有一个 Line 属性,其中包含发生匹配的原始行。您只能获取 Line 值,如下所示:

... |Select-String ... |Select-Object -ExpandProperty Line |Out-File filter.txt

【讨论】:

  • 这...仅仅因为它看起来像一个格式化后的字符串并不意味着它是一个字符串。
【解决方案2】:

这种方法似乎行得通。 Set-content 保存 matchinfo 对象的字符串版本,没有任何额外的空行,而不是 out-file 或 ">"。

get-content rockyou.txt | select-string '^[0-9]{2}[A-Z]{2}[a-z]{5}' -ca | 
  set-content filter.txt
get-content filter.txt

01ABcdefg

我想到你可能仍然想要文件名:

select-string '^[0-9]{2}[A-Z]{2}[a-z]{5}' rockyou.txt -ca | 
  % { $_.filename + ':' + $_.line } > filter.txt
cat filter.txt

rockyou.txt:01ABcdefg

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-01
    • 1970-01-01
    • 2020-05-24
    相关资源
    最近更新 更多