Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filenames and linenumbers for the matches of cat and grep

Tags:

grep

unix

cat

My code

$  *.php | grep google

How can I print the filenames and linenumbers next to each match?

like image 748
Léo Léopold Hertz 준영 Avatar asked Feb 26 '09 20:02

Léo Léopold Hertz 준영


People also ask

Can you grep for file names?

Grep can display the filenames and the count of lines where it finds a match for your word.

How do you name a cat file?

To create a new file, use the cat command followed by the redirection operator ( > ) and the name of the file you want to create. Press Enter , type the text and once you are done, press the CRTL+D to save the file. If a file named file1. txt is present, it will be overwritten.

What is the difference between grep and cat?

grep searches for occurrences of strings matching a regular expression in some text and prints lines that contain any of those occurrences. cat , on the other hand, prints all lines from the sources of input specified in the command.

How would I search a file for a particular line number using grep?

The -n ( or --line-number ) option tells grep to show the line number of the lines containing a string that matches a pattern. When this option is used, grep prints the matches to standard output prefixed with the line number.


2 Answers

grep google *.php

if you want to span many directories:

find . -name \*.php -print0 | xargs -0 grep -n -H google

(as explained in comments, -H is useful if xargs comes up with only one remaining file)

like image 145
cadrian Avatar answered Sep 22 '22 01:09

cadrian


You shouldn't be doing

$ *.php | grep

That means "run the first PHP program, with the name of the rest wildcarded as parameters, and then run grep on the output".

It should be:

$ grep -n -H "google" *.php

The -n flag tells it to do line numbers, and the -H flag tells it to display the filename even if there's only file. Grep will default to showing the filenames if there are multiple files being searched, but you probably want to make sure the output is consistent regardless of how many matching files there are.

like image 20
Alnitak Avatar answered Sep 26 '22 01:09

Alnitak