简体   繁体   中英

Grep inside files returned from ls and head

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 ls -t | head -5 | grep abaaba ls -t | head -5 | grep abaaba .

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM