14

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?

Pandu
  • 1,606
  • 1
  • 12
  • 23
  • I suggest changing the title to "how not lose color in grep" or something like that. Keep the current title inside the question text(description). This way, people will not incorrectly redirect questions here. It is better for community s it is a question that comes high in searches. – Sohail Si May 11 '22 at 08:48

2 Answers2

12
ls * | sort -n | xargs -d '\n' grep hello
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
4

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
Pandu
  • 1,606
  • 1
  • 12
  • 23