Neil
Neil

Reputation: 1698

Use grep to report back only line numbers

I have a file that possibly contains bad formatting (in this case, the occurrence of the pattern \\backslash). I would like to use grep to return only the line numbers where this occurs (as in, the match was here, go to line # x and fix it).

However, there doesn't seem to be a way to print the line number (grep -n) and not the match or line itself.

I can use another regex to extract the line numbers, but I want to make sure grep cannot do it by itself. grep -no comes closest, I think, but still displays the match.

Upvotes: 146

Views: 145105

Answers (9)

Phi
Phi

Reputation: 814

bash:

readarray a <<< $(grep -n Pattern File)
echo ${a[@]%%:*}
for l in ${a[@]%%:*}

ksh93/bash(watchout lastpipe)

grep -n Pattern File | while IFS=: read l z
do echo $l
done

Upvotes: 0

Mark Reed
Mark Reed

Reputation: 95375

I recommend the answers with sed and awk for just getting the line number, rather than using grep to get the entire matching line and then removing that from the output with cut or another tool. For completeness, you can also use Perl:

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

or Ruby:

ruby -ne 'puts $. if /pattern/' filename

Upvotes: 1

love_me_some_linux
love_me_some_linux

Reputation: 2741

try:

grep -n "text to find" file.ext | cut -f1 -d:

Upvotes: 213

Micael Levi
Micael Levi

Reputation: 6695

using only grep:

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

Upvotes: 2

JstRoRR
JstRoRR

Reputation: 3693

To count the number of lines matched the pattern:

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

To extract matched pattern

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

To display line numbers on which pattern was matched

grep -n "pattern" file.ext | cut -f1 -d:

Upvotes: 0

maverick
maverick

Reputation: 3022

Bash version

    lineno=$(grep -n "pattern" filename)
    lineno=${lineno%%:*}

Upvotes: 2

maverick
maverick

Reputation: 3022

All of these answers require grep to generate the entire matching lines, then pipe it to another program. If your lines are very long, it might be more efficient to use just sed to output the line numbers:

sed -n '/pattern/=' filename

Upvotes: 57

Chris
Chris

Reputation: 43

You're going to want the second field after the colon, not the first.

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

Upvotes: 0

brightlancer
brightlancer

Reputation: 2109

If you're open to using AWK:

awk '/textstring/ {print FNR}' textfile

In this case, FNR is the line number. AWK is a great tool when you're looking at grep|cut, or any time you're looking to take grep output and manipulate it.

Upvotes: 58

Related Questions