1

How do I grep recusively backwards. Let's say I have the following folders:

20170808
20170809
20170810

When I do grep -ri 'string' grep takes each folder in alphabetical order and searches for 'string'. How do I make it go backwards, from the last one to the first?

2

The order for grep -r will generally be random (not necessarily alphabetical), typically based on how the files are arranged in the directory and what possible re-ordering your grep implementation may do to optimise the directory traversal.

Here, with GNU grep 2.25:

$ grep -r . .
./4/c:c
./1/b:b
./2/a:a
./10/d:d

If you want a specific order, you have to give up on -r and give the list of files as arguments in the order you want.

For instance, in your case, and using zsh:

$ grep -H . ./**/*(D.On)
./4/c:c
./2/a:a
./1/b:b
./10/d:d

Here using On for reverse order by name. You can add the n qualifier for numeric sort:

$ grep -H . ./**/*(D.nOn)
./10/d:d
./4/c:c
./2/a:a
./1/b:b

(-H being another GNU grep extension to ensure the file name is always printed even if there's only one file. With other grep implementation, you can add an extra empty file as argument like /dev/null to make sure grep is passed at least two file names).

That is also very useful to zgrep rotated log files in chronological order (like access.log.10.gz ... access.log.2.gz, access.log.1, access.log) with:

zgrep something access.log*(nOn)

(though you can also sort by last modification time with zgrep something access.log*(Om) if those can be relied upon).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.