Search code examples
shellgrepxargscp

How to grep and copy files with spaces in their names


I have some files with spaces in their names. I want to pick all the files containing a specific text, and copy those files to another directory. I can use grep to do the first part, but got stuck piping the file name list to cp. cp always slices the file names according to the spaces. I've tried xargs --null, and that didn't do me good. Any practical solution?


Solution

  • Use --null options for both grep and xargs:

    grep --null --files-with-matches 'word' * | xargs --null cp -t "$target_dir"
    

    The --null options cause the commands to terminate the filenames with a zero byte instead of newlines.