如何使用 PowerShell 获取行号?

Sta*_*uff 6 powershell text-editing

我有一个简单的文本文件:

$ cat food.txt
Apples
Bananas
Carrots
Run Code Online (Sandbox Code Playgroud)

Linux/Cygwin

我可以想到几种在 Linux/Cygwin 中获取行号的方法:

$ nl food.txt
     1  Apples
     2  Bananas
     3  Carrots

$ cat -n food.txt
     1  Apples
     2  Bananas
     3  Carrots

$ less -NFX food.txt
      1 Apples
      2 Bananas
      3 Carrots
Run Code Online (Sandbox Code Playgroud)

电源外壳

我想出的最好的是:

2017 年 11 月 27更新:(1)添加了微调:Out-String -Stream强行将那些讨厌的对象文本化。(2) 注意:我正在寻找可以接受 PIPELINE INPUT 的东西。

PS C:\> function nl{$input | Out-String -Stream | Select-String '.*' | Select-Object LineNumber, Line}

PS C:\> cat .\food.txt | nl
LineNumber Line
---------- ----
         1 Apples
         2 Bananas
         3 Carrots
Run Code Online (Sandbox Code Playgroud)

有没有更简单的方法?更短?PowerShell 内置的东西?

Lot*_*ngs 2

我将我的行包装到一个函数中,您可以将其包含在您的 Powershell 配置文件之一中。

Function nl 
{
<# .Synopsis
    Mimic Unic / Linux tool nl number lines
   .Description
    Print file content with numbered lines no original nl options supported
   .Example
     nl .\food.txt
#>
  param (
    [parameter(mandatory=$true, Position=0)][String]$FileName
  )

  process {
    If (Test-Path $FileName){
      Get-Content $FileName | ForEach{ "{0,5} {1}" -f $_.ReadCount,$_ }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

示例输出:

> nl .\food.txt
    1 Apples
    2 Bananas
    3 Carrots
Run Code Online (Sandbox Code Playgroud)