Today's article is going to cover a command that falls into the "I don't use this often, but when I do it's awesome" category.
tac command is very similar to the
cat command in that it is used to concatenate and print files. However there is one very large difference, the
tac command does this in reverse, starting with the last line of the file and working its way up to the first line.
$ cat sample.txt This is line 1 This is line 2 This is line 3 This is line 4 This is line 5
$ tac sample.txt This is line 5 This is line 4 This is line 3 This is line 2 This is line 1
$ grep "line [3-5]" sample.txt | tac This is line 5 This is line 4 This is line 3
To be frank, I've only used tac on a hand full of occasions. Most of the times where I used
tac I later found out there was another way to get the same results. Either way here is a list of scenarios that I came up with where
tac could be useful.
$ tac sample.txt | head -n 2 | tac This is line 4 This is line 5
$ for x in `find ./ -type d | tac`; do echo $x; done ./directory2/1 ./directory2/91 ./directory2/81 ./directory2/
Got any other use cases? Throw them in the comments, I would love to hear how folks have used
tac in their daily lives.