Linux Command: rev
Reverse characters in each line of a file
The rev command reverses the character order of each line in a file or input stream. Each line is reversed independently โ the first character becomes the last and vice versa. rev is useful in text processing pipelines for tasks like extracting file extensions, reversing field order in combination with cut, parsing right-to-left data, and various string manipulation tricks. While it seems simple, rev is a powerful building block in Unix pipelines. Combined with cut and other tools, it enables extracting the last field from variable-length delimited data โ something that cut alone cannot do easily.
Syntax
rev [FILE]...Key Options
(no flags)โ rev has no flags โ it simply reverses each linefileโ Reverse lines from a filestdinโ Reverse lines from piped inputmultiple filesโ Process multiple files sequentiallywith cutโ Common pattern: extract last fieldpalindrome checkโ Compare original with reversed to check palindromes
Examples
Reverse a string
echo "Hello World" | revOutput: dlroW olleH
Extract file extension
echo 'archive.tar.gz' | rev | cut -d'.' -f1 | revOutput: gz
Get filename from path
echo '/var/log/nginx/access.log' | rev | cut -d'/' -f1 | revOutput: access.log
Pro Tips
- The rev | cut -d'x' -f1 | rev pattern extracts the last delimited field. This is one of the most useful rev tricks.
- rev reverses characters within each line. tac reverses the order of lines in a file. Different tools for different reversal tasks.
- rev may not correctly handle multi-byte UTF-8 characters on all implementations. Test with your locale if working with non-ASCII text.
Learn more: Full rev reference โ