Bash Script to Remove Blank Lines from File
grep -v '^$' filename or a Bash script with grep -v '^$' inputfile > outputfile to remove blank lines from a file.Examples
How to Think About It
Algorithm
Code
#!/bin/bash input_file="input.txt" output_file="output.txt" grep -v '^$' "$input_file" > "$output_file" echo "Blank lines removed. Output saved to $output_file."
Dry Run
Let's trace the input file with lines: 'Line 1', '', 'Line 3', '', '', 'Line 6' through the code.
Read line
Line 1
Check if line is blank
Line 1 is not blank, keep it
Read line
'' (empty line)
Check if line is blank
Line is blank, skip it
Read line
Line 3
Check if line is blank
Line 3 is not blank, keep it
Read line
'' (empty line)
Check if line is blank
Line is blank, skip it
Read line
'' (empty line)
Check if line is blank
Line is blank, skip it
Read line
Line 6
Check if line is blank
Line 6 is not blank, keep it
| Line Content | Action |
|---|---|
| Line 1 | Kept |
| Skipped | |
| Line 3 | Kept |
| Skipped | |
| Skipped | |
| Line 6 | Kept |
Why This Works
Step 1: Pattern Matching
The grep -v '^$' command matches lines that are empty (start and end with nothing) and excludes them with -v.
Step 2: Filtering Lines
Only lines that do not match the empty line pattern are printed, effectively removing blank lines.
Step 3: Redirecting Output
The filtered lines are saved to a new file using output redirection >.
Alternative Approaches
sed '/^$/d' input.txt > output.txt echo "Blank lines removed with sed."
awk 'NF' input.txt > output.txt echo "Blank lines removed with awk."
while IFS= read -r line; do [[ -n "$line" ]] && echo "$line" done < input.txt > output.txt echo "Blank lines removed with while loop."
Complexity: O(n) time, O(n) space
Time Complexity
The script reads each line once, so time grows linearly with the number of lines.
Space Complexity
Output is stored separately; memory usage depends on output size, but no extra large buffers are needed.
Which Approach is Fastest?
Using grep or sed is faster than a Bash loop because they are optimized native tools.
| Approach | Time | Space | Best For |
|---|---|---|---|
| grep -v '^$' | O(n) | O(n) | Simple and fast filtering |
| sed '/^$/d' | O(n) | O(n) | Powerful text editing |
| awk 'NF' | O(n) | O(n) | Flexible field-based filtering |
| while read loop | O(n) | O(n) | Learning and custom logic |
grep -v '^$' for a quick and simple way to remove blank lines.