Bash Script to Reverse Lines in a File
tac filename or a Bash script with tac to reverse lines in a file; for example, tac input.txt prints the lines in reverse order.Examples
How to Think About It
tac command does exactly this by printing lines in reverse order. Alternatively, you can read all lines into memory and print them in reverse sequence.Algorithm
Code
#!/bin/bash # Script to reverse lines in a file if [ $# -ne 1 ]; then echo "Usage: $0 filename" exit 1 fi filename="$1" if [ ! -f "$filename" ]; then echo "File not found: $filename" exit 1 fi # Use tac to reverse lines reversed_lines=$(tac "$filename") echo "$reversed_lines"
Dry Run
Let's trace reversing lines of a file with content: apple\nbanana\ncherry
Read file lines
Lines read: apple, banana, cherry
Reverse lines using tac
Output lines: cherry, banana, apple
Print reversed lines
Printed: cherry\nbanana\napple
| Step | Action | Result |
|---|---|---|
| 1 | Read lines | apple, banana, cherry |
| 2 | Reverse lines | cherry, banana, apple |
| 3 | Print lines | cherry\nbanana\napple |
Why This Works
Step 1: Using tac command
The tac command reads a file and outputs its lines in reverse order, which is exactly what we want to reverse lines.
Step 2: Checking file existence
The script first checks if the file exists to avoid errors when reading a non-existent file.
Step 3: Printing reversed lines
After reversing, the script prints the lines so the user sees the reversed content on the screen.
Alternative Approaches
awk '{line[NR] = $0} END {for (i=NR; i>0; i--) print line[i]}' filenamesed '1!G;h;$!d' filenamemapfile -t lines < filename; for ((i=${#lines[@]}-1; i>=0; i--)); do echo "${lines[i]}"; done
Complexity: O(n) time, O(n) space
Time Complexity
The script reads each line once and prints each line once, so time grows linearly with the number of lines.
Space Complexity
The entire file lines are stored in memory (by tac or arrays), so space grows linearly with file size.
Which Approach is Fastest?
Using tac is fastest and simplest; awk and sed are slower but useful if tac is missing; Bash arrays are good for learning but less efficient.
| Approach | Time | Space | Best For |
|---|---|---|---|
| tac command | O(n) | O(n) | Fastest and simplest for reversing lines |
| awk array | O(n) | O(n) | When tac is unavailable, moderate complexity |
| sed command | O(n) | O(n) | No tac or awk, but harder to read |
| Bash array loop | O(n) | O(n) | Learning Bash arrays, less efficient |
tac filename for a quick and efficient way to reverse lines in a file.