0
0
Bash-scriptingHow-ToBeginner · 2 min read

Bash Script to Print First n Lines of a File

Use the command head -n N filename in a Bash script to print the first N lines of a file named filename.
📋

Examples

InputN=3, filename contains:\nline1\nline2\nline3\nline4
Outputline1 line2 line3
InputN=1, filename contains:\nHello World\nSecond line
OutputHello World
InputN=5, filename contains:\nA\nB\nC
OutputA B C
🧠

How to Think About It

To print the first n lines of a file, think about reading the file from the top and stopping after n lines. The head command in Bash does exactly this by default or with the -n option to specify how many lines to show.
📐

Algorithm

1
Get the number n of lines to print.
2
Get the filename to read from.
3
Use the <code>head</code> command with <code>-n</code> option to read the first n lines.
4
Print the output to the screen.
💻

Code

bash
#!/bin/bash

# Number of lines to print
N=$1
# File to read
FILE=$2

# Print first N lines
head -n "$N" "$FILE"
Output
line1 line2 line3
🔍

Dry Run

Let's trace printing first 3 lines of a file named 'sample.txt' containing 4 lines.

1

Set variables

N=3, FILE='sample.txt'

2

Run head command

head -n 3 sample.txt

3

Output lines

Prints first 3 lines of sample.txt

Line NumberContent
1line1
2line2
3line3
💡

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

Using sed
bash
#!/bin/bash
N=$1
FILE=$2
sed -n "1,${N}p" "$FILE"
This uses sed to print lines 1 to N; useful if you want more control or to combine with other sed commands.
Using awk
bash
#!/bin/bash
N=$1
FILE=$2
awk "NR<=${N}" "$FILE"
Awk prints lines where the line number is less than or equal to N; good for more complex processing.

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.

ApproachTimeSpaceBest For
headO(n)O(1)Simple and fast line printing
sedO(n)O(1)Line printing with editing capabilities
awkO(n)O(1)Line printing with complex processing
💡
Always quote variables like "$N" and "$FILE" to handle spaces or special characters safely.
⚠️
Forgetting to pass both the number of lines and filename as arguments causes the script to fail or behave unexpectedly.