1

How do I search for files in a directory that contain a specific text and copy them to another directory ? I am using .ksh shell.

3
  • Are you talking about text within the files? Commented May 23, 2016 at 15:12
  • Well, thinking about this, it would be kind of a lengthy command, and you would be better off making a script specifically for this. Commented May 23, 2016 at 15:15
  • Are all these files in the same directory or do you have to search recursively ? If it's the latter, then is the destination directory under the same directory you are searching in ? Commented May 23, 2016 at 16:42

2 Answers 2

4

Do man xargs and look at the -I flag.

find /path/to/directory -type f -exec grep -il "your pattern" {} \; | xargs -I % cp % /dest/dir/

To save typing put this command in shell script :

#!/usr/bin/ksh 
# Script name: locate
find /path/to/directory -type f -exec grep -il "$1" {} \; | xargs -I % cp % /dest/dir/

To run type locate searchstring where searchstring is the text you are searching for.

1
  • @don_crissti Doesn't make sense, thanks for pointing out. Updated the answer
    – Rahul
    Commented May 23, 2016 at 16:47
2

You can simply do from the base directory you want to search

cp $(grep -r -l "the pattern" *) target_directory
  • grep -r means recusive
  • -l means list the file path not the match in it.

  • putting $() around the command will execute it and place the result in place in the outer command.

  • cp will take a list of files, and as long as the last path is a directory copy them all in there.

6
  • 1
    You should consider filenames that contain spaces and other "awkward" characters Commented May 23, 2016 at 22:56
  • Such evilness as files with spaces in their names!! How dare you bring that up LOL :)
    – Rob
    Commented May 24, 2016 at 13:22
  • 1
    the pet "nasty" around here is \n characters in filenames (perfectly legal; perfectly irritating). I tend to go for the pragmatic approach and ensure code will work with spaces but (only) try to ensure it works with \n characters. Commented May 24, 2016 at 13:25
  • ROFL LOVE IT! :) Never seen that before :)
    – Rob
    Commented May 24, 2016 at 13:32
  • 1
    touch $'hello\nworld' Commented May 24, 2016 at 14:10

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .