head Commandhead命令

Display the beginning of files显示文件的开头部分

What is head?什么是head?

The head command outputs the first part of files. By default, it displays the first 10 lines. This is incredibly useful for quickly previewing file contents without opening the entire file, especially with large files like logs.

head命令输出文件的开头部分。默认情况下,它显示前10行。这对于快速预览文件内容而无需打开整个文件非常有用,尤其是对于日志等大文件。

Basic Usage基本用法

$ head file.txt
# Shows first 10 lines (default)
$ head -n 20 file.txt
# Shows first 20 lines
$ head -5 *.txt
# Shows first 5 lines of all .txt files
$ head file.txt
# 显示前10行(默认)
$ head -n 20 file.txt
# 显示前20行
$ head -5 *.txt
# 显示所有.txt文件的前5行

Common Options常用选项

Option选项 Full Name完整名称 Description描述 Example示例
-n N lines行数 Print first N lines打印前N行 head -n 5 file.txt
-c N bytes字节 Print first N bytes打印前N字节 head -c 100 file.txt
-q quiet安静模式 Don't print file headers不打印文件标题 head -q file1 file2
-v verbose详细模式 Always print file headers始终打印文件标题 head -v *.txt

Practical Scenarios实际场景

Quick Log File Inspection快速检查日志文件

$ head -n 50 /var/log/syslog
# View first 50 log entries
$ head -n 50 /var/log/syslog
# 查看前50条日志条目

Extract Lines from File从文件中提取行

$ head -n 20 file.txt | tail -n 10
# Get lines 11-20 (first 20, then last 10 of those)
$ head -n 20 file.txt | tail -n 10
# 获取第11-20行(前20行,然后取其中的后10行)

Memory Tricks记忆技巧

🗣️ "head" = the head/top of something - Just like your head is at the top of your body!

🗣️ "head" = 某物的头部/顶部 - 就像你的头在身体的顶部!

📏 -n = Number of lines - Specify how many lines to show

📏 -n = Number of lines(行数) - 指定要显示多少行

🦠 -c = Character/byte count - Count bytes, not lines

🦠 -c = Character/byte count(字符/字节计数) - 计算字节而不是行