2

Let's say I have a directory structure like this:

/home/user/Desktop/test/testdir1/
/home/user/Desktop/test/testdir2/
/home/user/Desktop/test/testdir3/

and the same structure here:

/home/user/Documents/test/testdir1/
/home/user/Documents/test/testdir2/
/home/user/Documents/test/testdir3/

How can I move a file such as

/home/user/Desktop/test/testdir3/hello.txt

to the respective dir? (move only files)

3 Answers3

1
cd /home/user/Desktop/
find . -type f -print | while read f; do mv "$f" "/home/user/Documents/$f"; done

In order to handle spaces in the file names, you should:

  • Don't forget the " between source and targets.
  • Use absolute path.

Please take a look at this discussion, it is really helpful to handle spaces in file names.

Community
  • 1
  • 1
feihu
  • 1,935
  • 16
  • 24
1

There are many possible solutions... Some better than others, depending on the details.

If the testdir directory structure is flat,

for orig in /home/user/Desktop/test/*
do
    targ=${orig/Desktop/Documents}
    mv -i $orig $targ
done

If nested, and the target directories don't necessarily exist (will be problems if files have spaces in the names), and assuming you don't want the nested directories moved:

for orig in $(find /home/user/Desktop/test/ -type f -print)
do
    targ=${orig/Desktop/Documents}
    targ_dir=$(dirname "$targ")
    [ ! -d "${targ_dir}" ] && mkdir -p "${targ_dir}"
    mv -i "$orig" "$targ"
done

Those are just examples (warning: not tested, only typed...)

michael
  • 9,161
  • 2
  • 52
  • 49
1

I would use this command:

cd /home/user/Desktop/
find . -type d -print0 | xargs -0 -I'{}' echo mkdir -p '/home/user/Documents/{}'
find . -type f -print0 | xargs -0 -I'{}' echo mv '{}' '/home/user/Documents/{}'

Quoting the {} will ensure your script works with files containing spaces.

Also -print0 and -0 will pass your files from find to xargs using \0 as a delimiter. This will ensure your script works with wierd filenames.

Remove the echo when if the script seems to be good for you. The use of echo is to test the command without the side effects.

Lynch
  • 9,174
  • 2
  • 23
  • 34
  • Works nicely. Could you help me with one more thing? I need it to *copy* new directories from /home/user/Desktop/ to /home/user/Documents/ (and move the contents). Thanks. – user3427376 Mar 18 '14 at 22:34
  • execute this first: `find . -type d -print0 | xargs -0 -I'{}' echo mkdir -p '/home/user/Documents/{}'` – Lynch Mar 18 '14 at 23:01
  • Ah, I just noticed that will create folder with my file's names. (e.g. a folder name "test.txt") – user3427376 Mar 19 '14 at 00:37
  • the `-type d` part is very important it tells `find` to only output folder names, not file names – Lynch Mar 19 '14 at 01:20