linuxawkprintinggrepfind

How to print all lines that matches a particular string?


I am intending to print all the lines with their line numbers along with its location within a specific directory which matches a particular string.

Example..

/home/some_dir/file.txt -(LineNo) -(printing_thatlineitself)

I currently have 2 commands with me but both have some shortcomings

find /home/some_dir -type f -exec grep -Hn "Text To Find" {} \;

This above find command seems to work accurately but the issue is that it works quite slow

find /home/some_dir -type f -print0 | xargs -0 grep -Hn -C2 "Text To Find"

This command works comparatively quite faster but it provides inaccurate results. It even prints those lines where my inputted string is not present at all.

Can someone provide a solution that works accurately and is fast as well? PS / its fine if the solution doesn't use the find command to achieve this .it just has to be something I can directly run in CLI


Solution

  • As suggested in the comments , grep can be used to do this very efficiently

    grep -IHnr "Text to find" .
    

    -I : Process a binary file as if it did not contain matching data (to exclude binary files)

    -H : Print the filename for each match

    -n : Display the matched lines and their line numbers

    -r : Recursively search subdirectories listed

    "Text to find" : Search string

    . : Directory for search (current directory)