【问题标题】:Add index number to list of results of `Select-String`将索引号添加到“Select-String”的结果列表中
【发布时间】:2020-10-05 12:34:11
【问题描述】:

我需要在文件中搜索一个词,并在搜索结果中显示一个索引,以便于引用。

bash 中的命令是:

cat <file> | grep 'Table: ' | cat -n

到目前为止我在 Powershell 中所拥有的:

Get-Content <file> | Select-String 'Table: ' | Select-Object -Property LineNumber, Line

不幸的是,我没有意识到LineNumber 给出了文件中的实际行,而不是结果列表中的索引。

如何将 bash 命令转换为等效的 Powershell 命令?

【问题讨论】:

  • 我们可以在 bash in powershell 中做到这一点。 cat <file> | grep 'Table: ' | cat -nget-content <file> | select-string 'Table: ' | (foreach ($line in $(Get-Content -Path test.sh)){$count++; echo "$count $line"})

标签: powershell select-string select-object


【解决方案1】:

确实,Select-Object 输出的对象的.Line 属性表示给定输入文件中每个匹配项的行号。

PowerShell 没有直接等效于 cat -n(在输出的所有输入行前添加基于 1 的索引),但使用 ForEach-Object cmdlet 并不难:

$i = 0
Get-Content file.txt | Select-String 'Table: ' | ForEach-Object {
  "{0,6}`t{1}" -f ++$i, $_.Line
}

上面使用-fformat operator,左空格填充到6个字符(,6)第一个RHS操作数({0}),这是(递增)索引,++$i ,后跟一个制表符 (`t) 和第二个 RHS 操作数 ({1}),即手头的输入行 ($_.Line)。

【讨论】:

    【解决方案2】:

    只需使用 WSL:

    bash -c "cat <file> | grep 'Table: ' | cat -n"
    

    这将在 powershell 中运行 bash 代码。对于真正的 powershell 选项,您可以这样做:

    foreach ($line in $(Get-Content -Path <filepath> | Select-String 'Table: ')){
      $count++
      echo "$count $line"
    }
    

    【讨论】:

      猜你喜欢
      • 2015-05-29
      • 2012-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多