21

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?

17

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
36

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
done

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

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.