There are some string manipulation or alternation tasks that can be programmed in scripting or a programming language quite easily. For example, changing the case of a text in a file.
There are some tasks that are very commonly required when it comes to text manipulation. One such task is reversing lines in a file. When we say reversing the lines, it can mean two things: reversing the order of lines in a file or reversing each line in the file character-wise.
In this article, we will learn about the command ‘rev’ which deals with reversing lines in a file character-wise in place.
Rev Command in Linux
The ‘rev‘ command in Linux, which is available by default, is used to reverse lines in a file or entered as standard input by the user. The command basically searches for endline characters
('\n') which denote the end of a line and then reverse the characters of the line in place.
This is different from programs like ‘tac‘ which do not reverse the lines character-wise but only reverse the order of lines in the file. Now run the ‘rev’ command without any arguments to read the lines from standard input.
'Ctrl + C' to escape the input prompt.
Reverse Lines in a File in Linux
Now to reverse the lines in a file, pass the file name (or file path if it lies in a different directory) as the argument to rev.
$ rev filename/filepath
Let’s try this on a file ‘test.txt‘ with the following contents – first view the content of a file and then reverse the lines in a file.
$ cat test.txt $ rev test.txt
As you can see the order of the lines did not change, but the characters got reversed in place. You can also pass multiple files as arguments, in which case the output will be appended together in order of the arguments passed.
Let’s consider another file ‘test2.txt‘ with the contents:
$ cat test2.txt
Now, let’s pass both ‘test.txt‘ and ‘test2.txt‘ as arguments:
$ rev test.txt test2.txt
The user can then redirect the reversed output to another file if it is to be saved.
Today we learned about a small and simple but efficient command ‘rev‘ in Linux to reverse lines in a file character-wise. Note that rev is not an ‘inbuilt‘ function in Linux, but a binary file like any other program; delivered with almost every Linux distribution.
There might be certain *nix operating systems that do not have the program rev. Thanks for reading and let us know your thoughts in the comments below!