Windows equivalent to Linux `cat -n`?

4

1

In Linux, I can easily view any files with line number next to it with cat -n command.

sh-4.4$ cat test   
line 1             
line 2             
line 3             
sh-4.4$ 

sh-4.4$ cat test -n
     1  line 1     
     2  line 2     
     3  line 3     
sh-4.4$ 

What about Windows? Is there any similar command producing similar output?

type is one of the windows command to view content of the file.

C:\>type test.txt
line 1
line 2
line 3
C:\>

However, there is no -n option in it.

C:\>type /?
Displays the contents of a text file or files.

TYPE [drive:][path]filename

C:\>

This is what I'm expecting in Windows

C:\>(windows command to view and print line number) test.txt
     1  line 1     
     2  line 2     
     3  line 3     
C:\>

Sabrina

Posted 2018-03-10T02:28:41.640

Reputation: 1 703

Answers

2

Without installing a 3rd party tools, this can be done using Powershell, but there is a little bit of scripting complexity as seen below. What is nice about this script is that it will work with any DOS command that produces output.

$i = 1; cat food.txt | % {$i++;"$($i-1) `t $_"}

Note: Powershell has the cat command, as seen in the script, but it lacks line numbering. It is an alias for the PowerShell command get-content.

Here is the output:

1        Apples
2        Bananas
3        Carrots

Here is an example with a directory listing by simply executing dir in the script:

$i = 1; dir | % {$i++;"$($i-1) `t $_"}

Here is the output:

1        backgrounds
2        boot
3        inetpub
4        PerfLogs
5        Program Files
6        Program Files (x86)
7        Riot Games
8        Users
9        Windows
10       Reflect_Install.log

If you want line numbering to start at 0, then set $i = 0


Alternatively, you can install 3rd party cat program in Windows. There are many ports of UNIX commands to Windows, such as Cygwin and GnuWin32.

After installing Cygwin's base install:

C:\cygwin64\bin\cat -n food.txt

Outputs:

 1  apple
 2  banana
 3  bread
 4  cake

Keltari

Posted 2018-03-10T02:28:41.640

Reputation: 57 019

1It works very well with Powershell.

PS C:\> $i = 1; cat .\test.txt | % {$i++;"$($i-1)t $"} 1 line 1 2 line 2 3 line 3 PS C:> PS C:> $i = 1; get-content .\test.txt | % {$i++;"$($i-1) `t $"} 1 line 1 2 line 2 3 line 3 PS C:>` – Sabrina – 2018-03-10T07:19:32.067

2@Sabrina Glad it helped. Although, simply installing a 'cat' program might be more convenient in the long run – Keltari – 2018-03-10T07:28:10.647