How to Get Line Number from Grep?
The Following Grep Grep -R -E -N Coll * Will Display Fullpath/Filename: Coll I Would Like to Know What Line Has the Following Text, I Tried Adding -N, but It...
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>
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 '^[^:]+'
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-Efor 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.
#This shows only the line number. #i --> case-insensitive, c --> count var="APPLE";targetFile="targetFile.txt" numLin=$(grep -ic $var $targetFile); echo $numLine;