Use grep to display only line numbers

I have a file that may contain incorrect formatting (in this case, the appearance of the \\backslash template). I would like to use grep to only return line numbers where this happens (as in, the match was here, go to line # x and fix it).

However, there seems to be no way to print the line number ( grep -n ), not a match or line.

I can use another regular expression to extract line numbers, but I want grep to not be able to do this myself. grep -no comes closer, I think, but still displays a match.

+75
grep
Aug 05 '11 at 15:33
source share
8 answers

try the following:

 grep -n "text to find" file.ext |cut -f1 -d: 
+111
Aug 05 '11 at 15:43
source share

If you are open to using AWK:

 awk '/textstring/ {print FNR}' textfile 

In this case, FNR is the line number. AWK is a great tool when you look at grep | cut, or anytime you want to use grep output and manipulate it.

+30
Aug 07 2018-11-11T00:
source share

All of these answers require grep to generate all matching lines and then translate them into another program. If your lines are very long, it might be more efficient to use only sed to output line numbers:

 sed -n '/pattern/=' filename 
+18
Sep 18 '13 at 11:02
source share

Bash version

  lineno=$(grep -n "pattern" filename) lineno=${lineno%%:*} 
+2
Dec 6 '13 at 8:35
source share

You will need the second field after the colon, not the first.

grep -n "text to find" file.txt | cut -f2 -d:

0
Apr 23 '13 at 3:54 on
source share

To count the number of lines matching a pattern:

 grep -n "Pattern" in_file.ext | wc -l 

To retrieve the mapped pattern

 sed -n '/pattern/p' file.est 

To display the line numbers on which the pattern was mapped

 grep -n "pattern" file.ext | cut -f1 -d: 
0
Jun 28 '14 at 16:43
source share

I recommend sed and awk answers only to get the line number, instead of using grep to get the entire matching line, and then remove it from the output with cut or another tool. For completeness, you can also use Perl:

 perl -nE '/pattern/ && say $.' filename 

or Ruby:

 ruby -ne 'puts $. if /pattern/' filename 
0
Sep 10 '17 at 15:11
source share

using grep only:

grep -n "text to find" file.ext | grep -Po '^[^:]+'

0
Dec 23 '17 at 4:25
source share



All Articles