PowerShell 中 Bash 的 cat -n 的等价物是什么?

deo*_*oll 7 linux powershell bash command-line cat

我想要cat一个文件并输出它输出的每一行的行号。

但是,在 PowerShell 中,cat输出一个数组。因此,问题实际上变成了:如何在输出到控制台时打印每个项目的索引......?

我试过这样的事情:

$k = cat foo.js
$k | foreach { $index = $k.IndexOf($_) + 1; write "$index : $_"; } | more
Run Code Online (Sandbox Code Playgroud)

它给了我一些奇怪的结果。一些行号重复。什么是优雅且更可靠的方法来做到这一点?

小智 11

您可能会为此滥用 Select-String:

Select-String -Pattern .* -Path .\foo.txt | select LineNumber, Line
Run Code Online (Sandbox Code Playgroud)

示例输出:

LineNumber Line
---------- ----
         1 a   
         2     
         3 b   
         4     
         5 c   
Run Code Online (Sandbox Code Playgroud)


Dav*_*ill 5

我想 cat 一个文件并输出它输出的每一行的行号。

使用以下命令:

$counter = 0; get-content .\test.txt | % { $counter++; write-host "`t$counter` $_" }
Run Code Online (Sandbox Code Playgroud)

正如评论中指出的那样:

  • 使用write-output代替可能更好,write-host因为这允许对输出进行进一步处理。
  • echo 是别名 write-output

所以上面的命令变成了:

$counter = 0; get-content .\test.txt | % { $counter++; echo "`t$counter` $_" }
Run Code Online (Sandbox Code Playgroud)

示例输出:

> type test.txt
foo
//approved
bar
// approved
foo
/*
approved
*/
bar

> $counter = 0; get-content .\test.txt | % { $counter++; echo "`t$counter` $_" }
        1 foo
        2 //approved
        3 bar
        4 // approved
        5 foo
        6 /*
        7 approved
        8 */
        9 bar
>
Run Code Online (Sandbox Code Playgroud)

Cygwin 的示例输出cat -n用于比较:

$ cat -n test.txt
     1  foo
     2  //approved
     3  bar
     4  // approved
     5  foo
     6  /*
     7  approved
     8  */
     9  bar
$
Run Code Online (Sandbox Code Playgroud)