Windows 相當於 Linux 的「cat -n」?

Windows 相當於 Linux 的「cat -n」?

在 Linux 中,我可以使用指令輕鬆查看旁邊有行號的任何檔案cat -n

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$ 

那麼 Windows 呢?是否有類似的命令產生類似的輸出?

type是查看文件內容的 Windows 命令之一。

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

-n然而,其中沒有任何選項。

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

TYPE [drive:][path]filename

C:\>

這就是我在 Windows 中所期待的

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

答案1

在不安裝第三方工具的情況下,可以使用 Powershell 來完成此操作,但腳本編寫有點複雜,如下所示。這個腳本的優點在於它可以與任何產生輸出的 DOS 命令一起使用。

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

筆記:Powershell 有cat指令,如腳本所示,但缺少行編號。它是 PowerShell 指令的別名get-content

這是輸出:

1        Apples
2        Bananas
3        Carrots

dir這是一個透過簡單地在腳本中執行來列出目錄的範例:

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

這是輸出:

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

如果您希望行號從 0 開始,則設定 $i = 0


cat或者,您可以在 Windows 中安裝第 3方程式。 UNIX指令到Windows的移植很多,例如西格文GnuWin32

安裝 Cygwin 的基本安裝後:

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

輸出:

 1  apple
 2  banana
 3  bread
 4  cake

答案2

這是 Windows 中等同於 cat -n 的命令

findstr /n . "C:\Temp\myfile.txt"

顯示/n行號。這.是一個正規表示式,甚至可以匹配空白行。

為了更清楚地向讀者說明該命令的真正作用:

findstr.exe /n /r ".*"

相關內容