To reverse the order of lines in a file in Linux, you can use several command-line tools. Below are multiple methods with detailed explanations and examples:
1. Using tac
(Reverse cat
)
The simplest and most efficient method is the tac
command, which reverses lines in a file.
Syntax:
tac [input_file] > [output_file]
Example:
# Create a sample file
echo -e "Line 1\nLine 2\nLine 3\nLine 4" > input.txt
# Reverse lines and save to output.txt
tac input.txt > reversed.txt
# View the result
cat reversed.txt
Output:
Line 4
Line 3
Line 2
Line 1
2. Using awk
Use awk
to store lines in an array and print them in reverse order.
Syntax:
awk '{ lines[NR] = $0 } END { for (i=NR; i>=1; i--) print lines[i] }' [input_file]
Example:
awk '{ lines[NR] = $0 } END { for (i=NR; i>=1; i--) print lines[i] }' input.txt > reversed.txt
Output (same as tac
):
Line 4
Line 3
Line 2
Line 1
3. Using sed
A less common but creative approach with sed
.
Syntax:
sed '1!G;h;$!d' [input_file]
Example:
sed '1!G;h;$!d' input.txt > reversed.txt
How It Works:
1!G
: Append lines (except the first) to the hold space.h
: Overwrite the hold space with the current line.$!d
: Delete all lines except the last, which is printed.
4. Using nl
, sort
, and cut
Use line numbering and reverse sorting.
Syntax:
nl -ba -nrz [input_file] | sort -r | cut -f2-
Example:
nl -ba -nrz input.txt | sort -r | cut -f2- > reversed.txt
Explanation:
nl -ba -nrz
: Number all lines (-ba
), including empty ones, with right-justified zero-padded numbers.sort -r
: Sort lines in reverse order.cut -f2-
: Remove the line numbers.
5. Using perl
A Perl one-liner to reverse lines.
Syntax:
perl -e 'print reverse <>' [input_file]
Example:
perl -e 'print reverse <>' input.txt > reversed.txt
6. Using Python
A Python script to reverse lines.
Script:
python3 -c 'import sys; print("\n".join(reversed(sys.stdin.read().splitlines())),' < input.txt > reversed.txt
Summary of Methods
Method | Command | Use Case |
---|---|---|
tac | tac input.txt > reversed.txt | Fastest and simplest for most cases. |
awk | awk '{ ... }' input.txt | Flexible for scripting. |
sed | sed '1!G;h;$!d' input.txt | Compact but less intuitive. |
nl /sort | nl ... | sort -r | cut ... | Works without tac . |
perl | perl -e 'print reverse <>' input.txt | Perl one-liner. |
Python | python3 -c '...' < input.txt | Cross-platform scripting. |
Notes:
- Performance:
tac
is the fastest for large files.- Methods like
awk
orperl
load the entire file into memory, which may not be suitable for very large files.
- Edge Cases:
- Empty lines are preserved in the reversed output.
- Special characters (e.g.,
\n
) are handled correctly.
- Install
tac
:
- If
tac
is not available (e.g., on minimal systems), install it viacoreutils
:bash sudo apt-get install coreutils # Debian/Ubuntu
Example Workflow
Reverse a log file and analyze the latest entries first:
tac /var/log/syslog | less