2

I have a directory with a large number of files. I am attempting to search for text located in at least one of the files. The text is likely located in one of the more recent files. What is the command to do this? I thought it would look something like ls -t | head -5 | grep abaaba.

For example, if I have 5 files returned from ls -t | head -5: - file1, file2, file3, file4, file5, I need to know which of those files contains abaaba.

KPrince36
  • 2,886
  • 2
  • 21
  • 29
  • 2
    Normally, assuming you don't have white space (blanks, tabs, newlines, etc) in your file names or directory names, then: `ls -t | head -5 | xargs grep abaaba`. If you have white space around, then you have to work harder; it is not clear that `ls` is part of the answer (it is more probably a part of the problem). – Jonathan Leffler Jul 22 '15 at 23:21
  • xargs : abaaba : no such file or directory – KPrince36 Jul 22 '15 at 23:47
  • 2
    Did you include `xargs grep abaaba`? It sounds as if you omitted the `grep`. – Jonathan Leffler Jul 22 '15 at 23:48

2 Answers2

3

It's not really clear what you are trying to do. But I assume the efficiency is your main goal. I would use something like:

ls -t | while read -r f; do grep -lF abaaba "$f" && break;done

This will print only first file containing the string and stops the search. If you want to see actual lines use -H instead of -l. And if you have regex instead of mere string drop -F which will make grep run slower however.

ls -t | while read -r f; do grep -H abaaba "$f" && break;done

Of course if you want to continue the search I'd suggest dropping "&& break".

ls -t | while read -r f; do grep -HF abaaba "$f";done

If you have some ideas about the time frame, it's good idea to try find.

find . -maxdepth 1 -type f -mtime -2 -exec grep -HF abaaba {} \;

You can raise the number after -mtime to cover more than last 2 days.

Miroslav Franc
  • 1,282
  • 12
  • 13
  • 1
    Using your commands you will lose the information about the file names. The whole problem seems to be to find those file names, so, in my opinion, it's better to use `grep -H`. – MaxChinni Jul 23 '15 at 06:33
1

If you're just doing this interactively, and you know you don't have spaces in your filenames, then you can do:

grep abaaba $(ls -t | head -5)   # DO NOT USE THIS IN A SCRIPT

If writing this in an alias or for repeat future use, do it the "proper" way that takes more typing, but that doesn't break on spaces and other things in filenames.

If you have spaces but not newlines, you can also do

(IFS=$'\n' grep abaaba $(ls -t | head -5) )
Peter Cordes
  • 328,167
  • 45
  • 605
  • 847