I'm currently trying to learn more about bash scripting and all of that fun stuff, and I pieced together this little command:
find $path | xargs grep -n $pattern | awk '{print $1}'
While this DOES work, I was wondering if I was reinventing the wheel. Is there a better way to search through a directory, grep the files for a pattern, and return a list with line numbers?
Best Answer
Many
grep
variants implement a recursive option. E.g., GNU grepYou can then remove
find
:but this keeps more than the line number.
awk
is printing the first column. This examplewill be printed as
notice the
:import
in each line. You might want to usesed
to filter the output.Since a
:
could be present in the file name you can use the-Z
option of grep to output a nul character (\0) after the file name.with the same example as before will produce