Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question

2 Answers 2

up vote 17 down vote accepted

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
share|improve this answer

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.