如何使用头和尾部查看文件的开始或结尾?
head 和 tail 是 Unix-like 系统中用于快速查看文件开头和结尾的实用命令。1. head 默认显示文件前 10 行,使用 head -n 可指定行数;2. tail 默认显示文件后 10 行,使用 tail -n 可调整行数,tail -f 可实时追踪文件更新;3. 组合使用 head 和 tail 可提取特定行范围,例如 head -n 20 | tail -n 11 提取第 10 至 20 行;这些命令适用于日志检查、数据浏览及脚本开发,无需额外安装,直接内置于大多数 Linux 和 macOS 系统中。
If you're working in a Unix-like terminal and want to quickly check the start or end of a file without opening it fully, head and tail are two simple but powerful commands that can help. These tools are especially handy when dealing with large log files or data sets.
How to Use head to View the Start of a File
The head command displays the beginning of a file — by default, it shows the first 10 lines.
For example:
head filename.txtIf you want to see more or fewer lines, use the -n option followed by the number of lines you want:
head -n 20 filename.txt # Shows the first 20 lines
head -n -5 filename.txt # Shows everything *except* the last 5 linesThis is useful for checking headers in data files or quickly scanning the top of logs without loading the whole file.
Using tail to Check the End of a FileThe tail command works similarly but shows the end of a file. Like head, it defaults to 10 lines:
tail filename.txtYou can adjust the number of lines shown:
tail -n 15 filename.txt # Displays last 15 lines
tail -n 10 filename.txt # Skips first 10 lines, then shows the restOne particularly useful feature of tail is the -f option, which lets you "follow" a file in real time — great for monitoring log files:
tail -f /var/log/syslogThis will keep showing new lines as they're added to the file until you press Ctrl C to stop.
Combining head and tail for Specific Line RangesSometimes you might need to extract a specific section from a file. While neither head nor tail alone does this directly, combining them gives you more control.
For example, to get lines 10 through 20:
head -n 20 filename.txt | tail -n 11Here's how it works:
head -n 20 gets the first 20 lines.
Then tail -n 11 takes the last 11 lines of that output — which corresponds to lines 10–20 of the original file.
Another way to do this is using sed or awk, but for quick checks in the shell, stacking head and tail is fast and doesn’t require learning extra syntax.
These commands are straightforward but incredibly useful in daily work — whether you're debugging logs, inspecting data files, or scripting automation. Most modern Linux and macOS systems have them built-in, so no need to install anything extra.
基本上就这些。
以上是如何使用头和尾部查看文件的开始或结尾?的详细内容。更多信息请关注PHP中文网其他相关文章!