[WBEL-users] Linux Shell Scripting

Kirby C. Bohling kbohling at birddog.com
Sat Apr 30 14:19:40 CDT 2005


On Sun, May 01, 2005 at 02:41:15AM +0800, Andrew Vong wrote:

[snip]

> $ find /home/andrew/ | grep '\.doc' | xargs mv --target-directory=/backup/
> 
> This works for all files with no white spaces.

Try this:

$ find /home/andrew/ -name "*.doc" -print0 | xargs --null mv --target-directory=/backup/

I also slightly changed the semantics of your "grep" statement.  If
".doc" appears anywhere in your filename it'll get backed up.  I
believe with the find as I wrote it, you'll get only files that end
in ".doc".

If you really want your semantics try: -name "\*.doc\*".

Not sure if that's really a good idea.  If they have two files with
exactly the same name, you'll overwrite one of them, unless I'm not
understanding how "--target-directory" works.  So if you have:

/home/andrew/bar/a.doc
/home/andrew/foo/a.doc

You'll end up with only the last one that the find command outputs.

Now, if I was really interested in having only the doc files, and I
wanted the avoid the duplicate file name problem.

You'd do something like this:
( cd /home/andrew ; find . -name "*.doc" -print0 | \
tar -c --null -T - -f - ) | \
tar -C /backup -xvf - 

Oh, that's completely untested, so use with caution.
That will create the same directory structure for the files with the
.doc's. 

Use this command to test it:
( cd /home/andrew ; find . -name "*.doc" -print0 | \
tar -c --null -T - -f - ) | \
tar -C /backup -tvf -

The list of files you see will end up being created relative to
"/backup".  If the list of files looks right, it's probably
reasonable safe.  However, I'd back up everything if you aren't
really comfortable with what I'm doing during testing.

I'll explain all of it in detail if you want, but most of it is
pretty straight forward if you review the arguments on the man
pages.  About the only tricky thing is the usage of a sub-shell.  I
could probably avoid doing that if I thought about it hard, but I
don't care that much.  The only reason I used the sub-shell is to
get find to give me paths relative to "/home/andrew".  That way when
the first "tar" command runs, it runs from /home/andrew and has
paths relative to "/home/andrew".  Thus /backup will be structured
identically.  That might not be exactly the semantics you want, but
it appeared to be given what I saw of the original commands.

    Thanks,
        Kirby



More information about the Whitebox-users mailing list