Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grep get matched text's filename and line number in bash

Tags:

grep

bash

I want to do a grep in bash on a folder searching for the term foobar. I then want to output all of the matches along w/ the filename and line number where the occurrences were found. Is this possible?

I need the output to look like:

{{filename}}:{{line_number}} - {{matched_text}}
like image 561
Kyle Decot Avatar asked Dec 12 '22 01:12

Kyle Decot


2 Answers

grep -nrH 'regex' /dir/

-H is the option that adds filenames, -n adds line numbers, -r is recursive

I get filenames even without the -H unless there's only one file.

Add -i for case-insensitive

Add -E for extended regular expressions

like image 158
Dennis Williamson Avatar answered Jan 08 '23 00:01

Dennis Williamson


Use the -n or --line-number option

grep -n foobar
like image 31
mamills Avatar answered Jan 07 '23 22:01

mamills