0

Using only 1 command line, how do I write a command to that will do a long list of all files in the storage/file directory and pipe the output to a grep command that finds all items containing the word pizza?

Would it be this?:

ls -l /storage/file | grep pizza
  • echo storage/file/*pizza*? – twalberg Dec 16 '13 at 20:42
  • 1
    Are you intending to look for filenames that contain the word "pizza", files that contain the word "pizza" in the contents of the file, or lines of the ls output that contain the word "pizza" (which could include user or groups, or the filenames)? Here's a quick hint: whatever you do, the command will need to have the word "pizza" in it somewhere, which your current attempt doesn't. – Brian Campbell Dec 16 '13 at 20:42
  • I know you asked for grep but did you consider using find to search for the word pizza? find /storage/file -name pizza – KSdev Dec 16 '13 at 21:03
3

Here you go:

grep -l pizza /storage/file/*

This will print the names of all files under /storage/file/ that contain the word pizza.

If you want the long listing of these files, you can do any of these:

ls -l $(grep -l pizza /storage/file/*)
grep -l pizza /storage/file/* | xargs ls -l
  • grep has two modes of operation: it searches for a pattern in files listed on the command line OR if no files are listed then it will search in standard input, which can come from a pipe. So, method 1: grep pattern file1 file2 or method 2: some_cmd | grep pattern. The correct way depends on what you want to do. – janos Dec 16 '13 at 20:58
  • You only need to quote when the pattern contains characters that mean something in the shell. For "pizza" grep pizza is fine, but for "a pizza" you would have to write grep 'a pizza'. – janos Dec 16 '13 at 22:49
0

There is always your friend the find command.

find /storage/file -name '*pizza*' -exec ls -l {} \;

Note the single quotes around the name to prevent the shell from expanding the glob too soon. This form has the bonus being easily adapted to also looking IN said files:

find /storage/file -name '*pizza*' -exec grep cheese {} \;

This finds all files named with pizza in their file name and then shows all of the places they mention cheese.

Or did you mean just find all of the files talking about pizza in a directory and then long list them?

ls -l $(grep -l pizza /storage/file/*)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.