Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find and grep and print the file name and line number

I have a requirement to print all file name and line number which contain a text.

find . -name '*.cpp' -exec grep -n 'HELLO' {} \; > output.txt

but it's only printing the content and line number not the file name . How to achieve it? I am doing it on Solaris.

like image 228
CrazyC Avatar asked Jan 18 '26 06:01

CrazyC


1 Answers

Here's an option using awk instead of grep:

find . -name '*.cpp' -exec awk '/HELLO/ { print FILENAME, NR }' {} + > output.txt

Whenever the pattern is matched, the filename and line number are printed. I have used -exec {} + so that multiple filenames are passed as arguments to a single invocation of awk, which should be quicker if you have lots of files to search.

like image 55
Tom Fenech Avatar answered Jan 19 '26 19:01

Tom Fenech



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!