Get line number while using grep

GrepLine

Grep Problem Overview


I am using grep recursive to search files for a string, and all the matched files and the lines containing that string are print on the terminal. But is it possible to get the line numbers of those lines too??

ex: presently what I get is /var/www/file.php: $options = "this.target", but what I am trying to get is /var/www/file.php: 1142 $options = "this.target";, well where 1142 would be the line number containing that string.

Syntax I am using to grep recursively is sudo grep -r 'pattern' '/var/www/file.php'

One more question is, how do we get results for not equal to a pattern. Like all the files but not the ones having a certain string?

Grep Solutions


Solution 1 - Grep

grep -n SEARCHTERM file1 file2 ...

Solution 2 - Grep

Line numbers are printed with grep -n:

grep -n pattern file.txt

To get only the line number (without the matching line), one may use cut:

grep -n pattern file.txt | cut -d : -f 1

Lines not containing a pattern are printed with grep -v:

grep -v pattern file.txt

Solution 3 - Grep

If you want only the line number do this:

grep -n Pattern file.ext | gawk '{print $1}' FS=":"

Example:

$ grep -n 9780545460262 EXT20130410.txt | gawk '{print $1}' FS=":" 
48793
52285
54023

Solution 4 - Grep

grep -A20 -B20 pattern file.txt

Search pattern and show 20 lines after and before pattern

Solution 5 - Grep

grep -nr "search string" directory

This gives you the line with the line number.

Solution 6 - Grep

In order to display the results with the line numbers, you might try this

grep -nr "word to search for" /path/to/file/file 

The result should be something like this:

linenumber: other data "word to search for" other data

Solution 7 - Grep

When working with vim you can place

function grepn() {
	grep -n $@ /dev/null | awk -F $':' '{t = $1; $1 = $2; $2 = t; print; }' OFS=$':' | sed 's/^/vim +/' | sed '/:/s// /' | sed '/:/s// : /'
}

in your .bashrc and then

grepn SEARCHTERM file1 file2 ...

results in

vim +123 file1 : xxxxxxSEARCHTERMxxxxxxxxxx
vim +234 file2 : xxxxxxSEARCHTERMxxxxxxxxxx

Now, you can open vim on the correspondending line (for example line 123) by simply copying vim +123 file1 to your shell.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsaiView Question on Stackoverflow
Solution 1 - GrepMiro A.View Answer on Stackoverflow
Solution 2 - GrepcarlitoView Answer on Stackoverflow
Solution 3 - GrepCloud FallsView Answer on Stackoverflow
Solution 4 - GrepemilioView Answer on Stackoverflow
Solution 5 - GreprandomguyView Answer on Stackoverflow
Solution 6 - GrepFouad DjebbarView Answer on Stackoverflow
Solution 7 - GrepPorsche9IIView Answer on Stackoverflow