22

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?

bernie2436
  • 6,505
  • 22
  • 58
  • 69

2 Answers2

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

Anthon
  • 78,313
  • 42
  • 165
  • 222
18

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
Graeme
  • 33,607
  • 8
  • 85
  • 110