In this tutorial, you will learn how to reverse the file contents using three tips using linux commands.
Different Ways
- File Reversing using tac command
- File Reversing using sort command
- File Reversing using combination of nl and sort commands
1. Reversing File Contents using tac command
- Tac command is the reverse of cat command
- This command is used to display the file content in reverse order
- It takes only one argument which is the filename
- Use the below syntax to get the file contents in the reverse order.
Syntax
tac filename
Example
2. Reversing File Contents using sort command
- Sort command is used mainly used to arrange the file contents in sorted order
- This command is also used to reverse the file contents using the special option -r
NOTE
- By default, this command won’t reverse the file contents by number.
- So if you want to reverse the file, based on the number, then option -n should be used with option -r.
Options of Sort Command
S.N | Options | Description |
1. | sort –r(text based reversing) | This option is used to reverse the file contents based on the text (not number). |
2. | sort –nr(number based reversing) | This option is used to reverse the file contents based on the number (not text) |
Syntax
sort -r filename
Example
3. Reversing File Contents combination of nl and sort commands
- Here nl and sort commands are used together to reverse the file contents based on the numbering
- This is done by using the pipe command or pipe symbol (|)
- Pipe is joining two or more number of processes or commands
- So output of a command can be given as an input to another command via pipe. This is the advantage of using pipe in linux.
- First nl command is used to add the line numbers to file and this results will be given as an input to the sort command using pipe symbol (|)
- After that sort command will reverse the file contents with help of option -n (n for numerical sorting)
- Use the below syntax to get the file contents in the reverse order.
Syntax
nl filename | sort -rn
Where,
- I is a pipe (pipe symbol in linux)
- Here pipe will take input from nl command and send them as the input to sort command then sort command will sort the contents based on the options -rn.
Example