How to get line number from grep?

The following grep

grep -r -e -n coll *

will display

fullpath/filename: <tag-name>coll</tag-name>

I would like to know what line has the following text, I tried adding -n, but it did not work. I tried adding | grep -n *, but it did something weird.

What I would like to see (I don't care about format) is

fullpath/filename:10: <tag-name>coll</tag-name>
1

4 Answers

no need for -r & -e !

get line number of a pattern!

grep -n "pattern" file.txt

if you want to get only the line number as output add another grep command to it !

grep -n "pattern" file.txt | grep -Eo '^[^:]+'
1

You should put -e at the end of the options list: grep -rne coll *

To grep a pattern in a specific file, and get the matching lines:

grep -n <Pattern> <File> | awk -F: '{ print $1 }' | sort -u

or using cut as suggested by @wjandrea:

grep -n <Pattern> <File> | cut -f1 -d: | sort -u

where

  • <Pattern> is a quoted glob pattern (use option -E for regexp);
  • <File> is the file you are interested in;
  • the first pipe awk ... filters the line numbers in the output of grep (before : on each line);
  • the second pipe ensures that line numbers only appear once.
8
#This shows only the line number.
#i --> case-insensitive, c --> count
var="APPLE";targetFile="targetFile.txt"
numLin=$(grep -ic $var $targetFile);
echo $numLine;
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like