Bash Script to Print First n Lines of a File
head -n N filename in a Bash script to print the first N lines of a file named filename.Examples
How to Think About It
head command in Bash does exactly this by default or with the -n option to specify how many lines to show.Algorithm
Code
#!/bin/bash # Number of lines to print N=$1 # File to read FILE=$2 # Print first N lines head -n "$N" "$FILE"
Dry Run
Let's trace printing first 3 lines of a file named 'sample.txt' containing 4 lines.
Set variables
N=3, FILE='sample.txt'
Run head command
head -n 3 sample.txt
Output lines
Prints first 3 lines of sample.txt
| Line Number | Content |
|---|---|
| 1 | line1 |
| 2 | line2 |
| 3 | line3 |
Why This Works
Step 1: Using head command
The head command reads the start of a file and by default prints the first 10 lines, but with -n you specify exactly how many lines.
Step 2: Passing arguments
The script takes the number of lines and filename as arguments, making it flexible for any file and line count.
Step 3: Output
The command outputs the first n lines directly to the terminal, which you can redirect or use as needed.
Alternative Approaches
#!/bin/bash N=$1 FILE=$2 sed -n "1,${N}p" "$FILE"
#!/bin/bash N=$1 FILE=$2 awk "NR<=${N}" "$FILE"
Complexity: O(n) time, O(1) space
Time Complexity
The script reads only the first n lines, so time grows linearly with n, not the whole file size.
Space Complexity
No extra memory is used beyond storing the current line; output is streamed directly.
Which Approach is Fastest?
The head command is optimized for this task and generally faster than sed or awk for just printing lines.
| Approach | Time | Space | Best For |
|---|---|---|---|
| head | O(n) | O(1) | Simple and fast line printing |
| sed | O(n) | O(1) | Line printing with editing capabilities |
| awk | O(n) | O(1) | Line printing with complex processing |