Thursday, August 18, 2022

[FIXED] How do I get the dates of files in my output from a grep search?

Issue

I can search through all my files for a specific string and output in a txt document without issue. I can't seem to figure out how to also capture the date of the files in the output results.

grep -rnw '/my_path/' -e 'search_string' > list.txt

That works for finding the files, but when I try piping any additional commands like stat, date, or ls I can't seem to get the date of the files to output with file names.

grep -rnw '/my_path/' -e 'search_string' | stat -c %n':'%z > list.txt

This does not seem to work to get the dates of the files in my output.


Solution

The problem is that grep is outputting the line that match your string, not the file name, so that in your second example your trying to call stat on a string, not on a file!

You should add a -l parameter to your grep command in order to not output the matching line but the file that contains it. Try this:

grep -lrnw '/my_path/' -e 'search_string' | stat -c %n':'%z > list.txt

[EDIT] Anyway this would not work because the stat command does not accept input from a pipe. The solution is then

stat -c %n':'%z $(grep -lrnw '/my_path/' -e 'search_string') > list.txt


Answered By - luco5826
Answer Checked By - Pedro (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.