在 Linux Bash 中查詢檔案的行數
Yahya Irmak
2023年1月30日
Bash
Bash File
-
使用
wc計算 Bash 中的行數 -
使用
grep計算 Bash 中的行數 -
使用
cat計算 Bash 中的行數 -
使用
sed計算 Bash 中的行數 -
使用
awk計算 Bash 中的行數 -
使用
nl計算 Bash 中的行數
本文將解釋如何在 Linux Bash 中查詢檔案的行數。我們將給出 wc、grep、cat、sed、awk 和 nl 工具的示例用法。
在 Linux 中查詢行數的方法不止一種。讓我們建立示例檔案並使用不同的工具計算其行號。
下面是我們將在此示例中使用的檔案的內容。將其儲存為 example.txt。
line1
line2
line3
line4
line5
使用 wc 計算 Bash 中的行數
wc 命令的 -l 引數返回行數。
wc -l < example.txt

使用 grep 計算 Bash 中的行數
grep 命令的 -c 引數返回行數。
grep "" -c example.txt

使用 cat 計算 Bash 中的行數
cat 命令使用 -n 引數以編號格式將檔案內容列印到控制檯。我們用 tail 命令得到最後一行,用 awk 得到行號。
cat -n example.txt | tail -1 | awk '{print $1}'

使用 sed 計算 Bash 中的行數
我們可以通過以下使用 sed 命令找到檔案行數。
sed -n '$=' example.txt

使用 awk 計算 Bash 中的行數
awk 工具可用於查詢檔案行數。
awk 'END{print NR}' example.txt

使用 nl 計算 Bash 中的行數
nl 命令使用 -n 引數以編號格式將檔案內容列印到控制檯。我們用 tail 命令得到最後一行,用 awk 得到行號。
nl example.txt | tail -1 | awk '{print $1}'

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Yahya Irmak
Yahya Irmak has experience in full stack technologies such as Java, Spring Boot, JavaScript, CSS, HTML.
LinkedIn