将文件从一个文件夹结构移动到另一个

时间:2014-03-17 03:08:02

标签: bash file ubuntu terminal directory

我们说我的目录结构如下:

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

和这里的结构相同:

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

如何移动

等文件
/home/user/Desktop/test/testdir3/hello.txt

到各自的目录? (仅移动文件)

3 个答案:

答案 0 :(得分:1)

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

为了处理文件名中的spaces,您应该:

  • 不要忘记源和目标之间的"
  • 使用绝对路径。

请查看此discussion,在文件名中处理spaces非常有用。

答案 1 :(得分:1)

有许多可能的解决方案......有些比其他解决方案更好,具体取决于具体细节。

如果testdir目录结构是扁平的,

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

如果嵌套,并且目标目录不一定存在(如果文件中名称中有空格则会出现问题),并假设您不希望移动嵌套目录:

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

这些只是示例(警告:未测试,仅键入...)

答案 2 :(得分:1)

我会使用这个命令:

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/{}'

引用{}将确保您的脚本适用于包含空格的文件。

此外,-print0-0会将您的文件从find传递到xargs,并使用\0作为分隔符。这将确保您的脚本使用奇怪的文件名。

如果脚本对您有好处,请删除echo。使用echo是为了测试命令而没有副作用。