-2

I always need to find some key words in thousands of feedback and locate it in which line. I used to redirect feedback to a file, and open file wiith vim, and execute vim command :set nu to do this. But it is pretty inconvenient and cause some unnecessary disk IO.
So I wonder if there is a command can achive below results:

$ sudo my-command | line-number-command | grep 'foo\|bar'
114  bla bla bla foo
514  bla bar bla bla
810  foo bla bla bla
1919 bla bla bar bla
fajin yu
  • 435
  • 5
    Well there's nl - but grep itself has a -n option for line numbering – steeldriver Dec 24 '20 at 02:20
  • Honest question - Why put that in a comment rather than as an answer? – NotTheDr01ds Dec 24 '20 at 02:30
  • @NotTheDr01ds because the question was obviously just going to get downvoted and closed since the OP could've answered it themselves with a glance at the grep man page or looking at past questions here or just a quick google and sometimes when you answer a question like that your answer also gets downvoted for encouraging such questions. So if you feel like throwing the OP a bone then doing so in a comment is reasonable. – Ed Morton Dec 26 '20 at 23:14
  • 1
    Makes sense - Thanks for the info. – NotTheDr01ds Dec 27 '20 at 00:04

2 Answers2

3

In your case, when you only need to number the lines which match a pattern, you don't need an additional command: it's simpler and much more efficient to simply use the -n option of grep:

$ sudo my-command | grep -n 'foo\|bar'
114:  bla bla bla foo
514:  bla bar bla bla
810:  foo bla bla bla
1919: bla bla bar bla

It would be a huge waste of ressources to prefix all lines of the input file with numbers (and in the process create an additional intermediate file/pipe), if you only want to print a small percentage of them.

(BTW, you can also use grep -n $ to number all lines! This may be less efficient than nl, but not that much, and since we are more likely to forget nl than to forget grep, it might be easier to remember.)

Max
  • 246
1

sudo my-command | cat -n | grep 'foo\|bar'

Or, as steeldriver mentioned in the comments, nl is probably a better answer.

NotTheDr01ds
  • 3,547