Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reverse lines of a text file?

I'm writing a small shell script that needs to reverse the lines of a text file. Is there a standard filter command to do this sort of thing?

My specific application is that I'm getting a list of Git commit identifiers, and I want to process them in reverse order:

git log --pretty=oneline work...master | grep -v DEBUG: | cut -d' ' -f1 | reverse 

The best I've come up with is to implement reverse like this:

... | cat -b | sort -rn | cut -f2- 

This uses cat to number every line, then sort to sort them in descending numeric order (which ends up reversing the whole file), then cut to remove the unneeded line number.

The above works for my application, but may fail in the general case because cat -b only numbers nonblank lines.

Is there a better, more general way to do this?

like image 764
Greg Hewgill Avatar asked Jan 06 '09 21:01

Greg Hewgill


People also ask

How can I reverse the order of lines in a file?

-r – reverse order.

How do you reverse a line in notepad?

From the Edit menu, click Line Operations → Sort Lines Lexicographically Descending. The lines in the text file are now reversed.

How do you flip words in notepad?

You can mark the string that should be reversed and hit Ctrl + R .


2 Answers

In GNU coreutils, there's tac(1)

like image 73
Vinko Vrsalovic Avatar answered Sep 25 '22 17:09

Vinko Vrsalovic


There is a standard command for your purpose:

tail -r file.txt 

prints the lines of file.txt in reverse order!

like image 22
porg Avatar answered Sep 21 '22 17:09

porg