The cart is empty

In the Linux operating system, users often encounter the need to view or process text data stored in files. For these purposes, several basic commands come in handy, including tail and head. These commands are particularly useful for working with logs and other files that are continuously growing.

The tail Command

The tail command in Linux is used to display the last part of a text file to the standard output. By default, tail displays the last 10 lines of a file. It's especially useful for monitoring recent changes in a file, such as monitoring the current state of log files.

Basic usage:

tail [options] [file]

Examples of using the tail command:

  • Displaying the last 10 lines of a file:
    tail file.txt
    ​
  • Displaying the last 20 lines of a file:
    tail -n 20 file.txt
    ​
  • Monitoring file changes in real-time:
    tail -f file.txt
    ​

The head Command

On the other hand, the head command is used to display the first part of a text file. Like tail, head by default displays the first 10 lines of a file.

Basic usage:

head [options] [file]

Examples of using the head command:

  • Displaying the first 10 lines of a file:
    head file.txt
    ​
  • Displaying the first 20 lines of a file:
    head -n 20 file.txt
    ​

Combining the tail and head Commands

The tail and head commands can be effectively combined to obtain specific parts of files. For example, if you want to extract lines 50 to 60 from a large file, you can use a combination of both commands using a pipe |.

head -n 60 file.txt | tail -n 11

 

This example first uses the head command to retrieve the first 60 lines of the file, and then tail is used to display the last 11 lines from those 60, effectively returning lines 50 to 60.

 

The tail and head commands are invaluable tools in Linux for working with text files. They allow users to quickly view, monitor, and manipulate data stored in files, which is essential for efficient command-line work. As demonstrated, by combining these commands, even greater flexibility and efficiency can be achieved when working with files.