I have this grep command to find files without the word Attachments in them.

grep -L -- Attachments *

I want to move all the files that are output from that command. How do I do that in bash? Do I use a pipe? Do I use a more wordy if/then statement in a full-on script?

2 Answers 2


What you want to do is use a pipe and greps -Z option:

Using GNU grep and mv

grep -LZ -- Attachments * | xargs -0 mv -t target_directory

The -Z combined with xargs -0 handles any filenames with special characters.

Using BSD grep and mv (like on MacOS X)

grep -L --null -- Attachments * |
while IFS= read -r -d "" file; do 
    mv "./$file" target_directory

On BSD, grep -Z means decompress, grep --null works on both BSD and GNU. BSD mv lacks option -t


If you know that none if the file names contain new lines, tabs, spaces or glob combinations that may produce a match, this may be easier for a one off case:

mv $(grep -L Attachments *) dest_dir

You must log in to answer this question.

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