Here are three different ways to print the last line of a file in Linux:

  1. Using tail command: The tail command is a popular command used to display the end of a file. By default, the tail command displays the last 10 lines of a file, but we can use the -n option to specify the number of lines to display. To print the last line of a file, we can use the tail command with the -n 1 option, which displays only the last line of the file.

Example:

tail -n 1 filename.txt

  1. Using sed command: The sed command is a stream editor used to perform basic text transformations on an input stream. We can use the sed command to print the last line of a file by using the $ symbol, which represents the last line of the file.

Example:

sed -n '$p' filename.txt

  1. Using awk command: The awk command is a powerful text processing tool used to manipulate and analyze text data. We can use the awk command to print the last line of a file by using the NR variable, which represents the total number of lines in the file, and printing the last line using the if statement.

Example:

awk '{if(NR==n) print}' n=$(wc -l < filename.txt) filename.txt

Note: All three commands will output the last line of the file 'filename.txt'.

 

Previous Post Next Post