[Bash] Head and Tail

Zhentiw發表於2024-05-16

The head command is used to display the beginning of a file or the first few lines of input. It's a useful command for quickly viewing the start of a file without opening the entire file.

head [options] [file]

Display the first 10 lines of a file (default behavior):

head filename.txt

Display a specific number of lines:

head -n 5 filename.txt

This command displays the first 5 lines of filename.txt.

Display the first few bytes of a file:

head -c 20 filename.txt

This command displays the first 20 bytes of filename.txt.

Tail

Since we learned the head command today, let's pair it with the tail command, which is used to display the end of a file or the last few lines of input.

tail [options] [file]

Display the last 10 lines of a file (default behavior):

tail filename.txt

Display a specific number of lines from the end:

tail -n 5 filename.txt

Display the last few bytes of a file:

tail -c 20 filename.txt

Follow the content of a file as it grows (useful for log files):

tail -f filename.txt

相關文章