Bash Script to Print Last N Lines of a File
Use the
tail -n N filename command in Bash to print the last N lines of a file, where N is the number of lines you want to see.Examples
Inputfile.txt content:
line1
line2
line3
line4
line5
Command: tail -n 3 file.txt
Outputline3
line4
line5
Inputfile.txt content:
apple
banana
cherry
Command: tail -n 1 file.txt
Outputcherry
Inputfile.txt content:
one
two
three
four
five
six
seven
Command: tail -n 0 file.txt
Output
How to Think About It
To print the last n lines of a file, think about reading the file from the end instead of the beginning. The
tail command in Bash is designed to do exactly this by default. You just need to specify how many lines you want with the -n option.Algorithm
1
Get the number of lines n to print from the user or script argument.2
Get the filename from the user or script argument.3
Use the <code>tail -n n filename</code> command to extract the last n lines.4
Print the output to the screen.Code
bash
#!/bin/bash # Check if two arguments are given if [ "$#" -ne 2 ]; then echo "Usage: $0 <number_of_lines> <filename>" exit 1 fi n=$1 file=$2 tail -n "$n" "$file"
Output
line3
line4
line5
Dry Run
Let's trace printing last 3 lines of file.txt containing 5 lines.
1
Input arguments
n=3, file=file.txt
2
Run tail command
tail -n 3 file.txt
3
Output lines
line3 line4 line5
| Step | Command | Output |
|---|---|---|
| 1 | Set n=3, file=file.txt | |
| 2 | tail -n 3 file.txt | line3 line4 line5 |
Why This Works
Step 1: Using tail command
The tail command reads the file from the end and prints lines.
Step 2: Option -n
The -n option tells tail how many lines to print from the end.
Step 3: Arguments validation
The script checks if the user provides exactly two arguments: number of lines and filename.
Alternative Approaches
Using sed command
bash
sed -n "$(( $(wc -l < filename) - n + 1 )),$ p" filenameThis uses sed to print lines from calculated start line to end; less efficient for large files.
Using awk command
bash
awk -v n=3 'NR>=(NR-n+1)' filename
Awk can print last n lines but requires reading whole file; more complex syntax.
Complexity: O(n) time, O(1) space
Time Complexity
The tail command reads only the last part of the file, so it runs in linear time relative to the number of lines requested, not the whole file.
Space Complexity
It uses constant extra space because it streams output without loading the entire file into memory.
Which Approach is Fastest?
tail is fastest and simplest for this task compared to sed or awk which may read the whole file.
| Approach | Time | Space | Best For |
|---|---|---|---|
| tail -n | O(n) | O(1) | Quickly printing last lines of large files |
| sed | O(m) | O(1) | When you want line ranges but less efficient for large files |
| awk | O(m) | O(1) | Complex processing but slower for just last lines |
Use
tail -n for a simple and efficient way to get last lines of a file.Forgetting to quote variables can cause errors if filenames or numbers contain spaces.