0

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.

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
Shawnh
  • 13
  • 5
  • What's the output supposed to look like? – Benjamin W. Jul 01 '20 at 17:40
  • You don't have to (or actually should not) update the question to include a solution; the solution lives in a separate answer, and you should accept and/or upvote it instead of editing the question. – Benjamin W. Jul 01 '20 at 17:52

2 Answers2

1

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
luco5826
  • 404
  • 3
  • 6
  • Okay! solution worked along with your version. grep -lrnw '/path/' -e 'string' | xargs stat -c %n':'%z > file.txt – Shawnh Jul 01 '20 at 17:59
0

Here's a solution with find -exec that avoids unquoted expansions:

find /my_path \
    -type f \
    -exec grep -qw 'search_string' {} \; \
    -exec stat -c '%n:%z' {} +

where

  • type f – only look at files
  • -exec grep -qw 'search_string' {} \; – only pass files that contain the word search_string to the next command
  • -exec stat -c '%n:%z' {} + – run stat as few times as possible for the files found
Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
  • Thank you for helping with the alternative find command. I was hoping to have both of them, and that works. They both ran identical times on my tests - but now I have 2 ways to modify. – Shawnh Jul 01 '20 at 20:21