Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change the order in which grep looks at files/prints results?

Tags:

linux

grep

bash

gnu

I have a directory with a bunch of files with numerical filenames. They don't have leading zeroes, so if I do something like grep hello * in that directory I might get something like this:

22:hello, world!
6:hello
62:"Say hello to them for me."

I'd rather have the result be like this:

6:hello
22:hello, world!
62:"Say hello to them for me."

The first thought that occured to me was to sort the results numerically with grep hello * | sort -n but then I lose grep's colors, which I'd like to keep. What's the best way to do that?

like image 702
pandubear Avatar asked Jun 14 '13 02:06

pandubear


2 Answers

ls * | sort -n | xargs -d '\n' grep hello
like image 157
John Kugelman Avatar answered Sep 23 '22 14:09

John Kugelman


Ah -- grep suppresses its colors when its output is a pipe (which is probably a good thing). But this can be overridden by supplying --color=always, which makes the | sort -n approach work:

grep --color=always hello * | sort -n
like image 40
pandubear Avatar answered Sep 21 '22 14:09

pandubear