Bash Script to Print Specific Line from File
Use
sed -n 'N{p;q;}' filename where N is the line number to print a specific line from a file in Bash.Examples
Inputfile.txt content:
Line1
Line2
Line3
Command: sed -n '2{p;q;}' file.txt
OutputLine2
Inputfile.txt content:
Apple
Banana
Cherry
Date
Command: sed -n '4{p;q;}' file.txt
OutputDate
Inputfile.txt content:
One
Two
Three
Command: sed -n '5{p;q;}' file.txt
Output
How to Think About It
To print a specific line from a file, think of reading the file line by line until you reach the line number you want. Then, print that line and stop reading further to save time.
Algorithm
1
Get the line number N to print.2
Open the file and read lines one by one.3
When the current line number equals N, print the line.4
Stop reading the file after printing the line.Code
bash
#!/bin/bash line_number=$1 file=$2 sed -n "${line_number}{p;q;}" "$file"
Output
Line2
Dry Run
Let's trace printing line 2 from a file with content: Line1, Line2, Line3
1
Set inputs
line_number=2, file='file.txt'
2
Run sed command
sed reads lines one by one
3
At line 2
Print 'Line2' and quit
| Line Number | Line Content | Action |
|---|---|---|
| 1 | Line1 | Skip |
| 2 | Line2 | Print and quit |
Why This Works
Step 1: Use sed with -n option
The -n option tells sed not to print anything by default.
Step 2: Specify line number and commands
The 'N{p;q;}' means: at line N, print (p) and quit (q) immediately.
Step 3: Stop reading after printing
Quitting early saves time by not reading the whole file.
Alternative Approaches
Using awk
bash
awk 'NR==N {print; exit}' file.txtAwk reads lines and prints the Nth line, then exits early; easy and readable.
Using head and tail
bash
head -n N file.txt | tail -n 1This reads the first N lines then prints the last one; less efficient for large files.
Complexity: O(N) time, O(1) space
Time Complexity
The script reads lines up to line N, so time grows linearly with N.
Space Complexity
Uses constant extra space since it processes one line at a time.
Which Approach is Fastest?
Using sed or awk with early exit is fastest; head and tail read more lines than needed.
| Approach | Time | Space | Best For |
|---|---|---|---|
| sed with quit | O(N) | O(1) | Fast line extraction with minimal overhead |
| awk with exit | O(N) | O(1) | Readable and efficient for line extraction |
| head and tail | O(N) | O(1) | Simple but less efficient for large files |
Use
sed -n 'N{p;q;}' filename for fast printing of a specific line.Forgetting to quit after printing causes the whole file to be processed unnecessarily.