Home > Enterprise >  grep -l stil show path to file
grep -l stil show path to file

Time:11-10

I am writing a script to search all files from a directory/root based on a keyword input.

echo "Enter keyword"
read key
grep -r -l . -e "$key"

If I search for "hei", which I know is located in a file called mem.c, it prints /folder/mem.c, and not only the filename. Do I have some wrong arguments or is it supposed to be like that?

Additional question, is there a way to store these filenames, and copy them into another directory if there is a match in the keyword? Or maybe it is possible to loop through the files found with grep?

CodePudding user response:

This is what grep -l does: print the path of matching files. If you want to print only the base name of the files you can pipe the result to some command that does that. Example:

grep -rlZ "$key" . | xargs -0 -n1 basename

Storing the file names in a file is just a matter of redirection:

grep -rlZ "$key" . | xargs -0 -n1 basename > mylist.txt

To copy the matching files somewhere you will need their path, not just their base name. Assuming you want to copy them all in the same destdir directory and you have no name conflicts, you could use find:

find . -type f -exec grep -l "$key" {} \; -exec cp -f {} destdir \;
  • Related