在 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