3

考虑一个files.txt类似(但不限于)的文件列表(例如)

/root/
/root/lib/
/root/lib/dir1/
/root/lib/dir1/file1
/root/lib/dir1/file2
/root/lib/dir2/
...

如何将指定的文件(不是文件夹中的任何其他内容也指定)复制到我选择的位置(例如~/destination),其中a)完整的文件夹结构 b) N 个文件夹组件(在示例中只是/root/)从小路?

我已经设法使用

cp --parents `cat files.txt` ~/destination

复制具有完整文件夹结构的文件,但是这会导致所有文件都在~/destination/root/...我希望将它们放入时结束~/destination/...

4

2 回答 2

1

我想我通过使用 GNU 找到了一个非常好的简洁的解决方案tar

tar cf - -T files.txt | tar xf - -C ~/destination --strip-components=1

请注意--strip-components允许从文件名开头删除任意数量的路径组件的选项。

不过有一个小问题:它似乎tar总是“压缩”中提到的文件夹的全部内容files.txt(至少我找不到忽略文件夹的选项),但使用以下方法最容易解决grep

cat files.txt | grep -v '/$' > files2.txt
于 2017-04-25T22:53:21.763 回答
0

这可能不是最优雅的解决方案 - 但它有效:

for file in $(cat files.txt); do
    echo "checking for $file"
    if [[ -f "$file" ]]; then
        file_folder=$(dirname "$file")
        destination_folder=/destination/${file_folder#/root/}
        echo "copying file $file to $destination_folder"
        mkdir -p "$destination_folder"
        cp "$file" "$destination_folder"
    fi
done

我看过cpand rsync,但看起来如果你先cd进入,他们会受益更多/root

但是,如果您cd事先对正确的目录进行了操作,则始终可以将其作为子shell 运行,这样子shell 完成后您将返回到原始位置。

于 2017-04-25T21:38:27.403 回答