tmath
tmath

Reputation: 564

Order grep output by second token

I am grepping for log output in many log files. I want the output of the grep command to be ordered by the time, which is the second token of every log line. The log lines are preceded with the date in the following format:

[2019-Jan-18 09:46:40.385624]

The logs are only ever from today so ordering only by the time will suffice.

I am using the following command to grep for a string:

grep "needle" /path/to/logs/*

How can I order the output by ascending time? I have tried piping to the sort command

grep "needle" /path/to/logs/* | sort

but that only sorts by the filename.

Upvotes: 1

Views: 1152

Answers (1)

Romeo Ninov
Romeo Ninov

Reputation: 7235

To force sort to sort second column you should use command like:

grep "needle" /path/to/logs/* | sort -k2

To use for sort only second column you should use it on this way:

grep "needle" /path/to/logs/* | sort -k2,2

Upvotes: 1

Related Questions