What is the equivalent of Bash's cat -n in PowerShell?

I want to cat a file and output the line number of each line it outputs.

However, in PowerShell, cat outputs an array. Hence the question effectively becomes: How do I print the index of each item while it's being output to the console...?

I tried something like this:

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

It gave me some weird results. Some line numbers repeated. What is an elegant and more reliable way to do this?


Solution 1:

I want to cat a file and output the line number of each line it outputs.

Use the following command:

$counter = 0; get-content .\test.txt | % { $counter++; write-host "`t$counter` $_" }

As pointed out in the comments:

  • It may be better to use write-output instead of write-host as this allows further processing of the output.
  • echo is an alias for write-output

So the above command becomes:

$counter = 0; get-content .\test.txt | % { $counter++; echo "`t$counter` $_" }

Example output:

> 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
>

Example output from Cygwin cat -n for comparison:

$ cat -n test.txt
     1  foo
     2  //approved
     3  bar
     4  // approved
     5  foo
     6  /*
     7  approved
     8  */
     9  bar
$

Solution 2:

You potentially abuse Select-String for that:

Select-String -Pattern .* -Path .\foo.txt | select LineNumber, Line

Example output:

LineNumber Line
---------- ----
         1 a   
         2     
         3 b   
         4     
         5 c