使用空文件复制目录树

时间:2016-01-15 17:04:44

标签: macos bash

我希望创建一个包含空文件的文件夹树的副本。源文件夹中的文件不为空,但我希望目标文件夹中的文件为空。 (我认为我不能只使用软/硬链接,因为我在Mac OS X上,对吧?)这是跟踪很多大型视频的许多外置硬盘的内容其中的文件。

我发现rsync -a -f"+ */" -f"- *" source/ destination/要复制文件夹,但我找不到创建空文件的方法(我尝试了一个tcsh foreach,但由于文件夹名称中有空格而失败了)

感谢您的帮助!

3 个答案:

答案 0 :(得分:2)

根据ursusd8的答案,这里有一个可以在bash版本4中运行的递归解决方案,如果你已经安装了...

shopt -s globstar
cd /path/to/source/
for f in **/*; do
  mkdir -p "/path/to/target/${f%/*}"   # make the containing directory if required
  touch "/path/to/target/$f"           # make a zero-length file
done

这比mkdir命令运行的次数多得多,但速度很快。请注意,除非您使用MacPortshomebrew等明确安装了bash 4,否则bash 4可能无法在您的系统上使用。

更长的选择是分离创建目录树和触摸文件的步骤:

cd /path/to/source/
find . -type d -exec mkdir -p /path/to/target/{} \;
find . -type f -exec touch /path/to/target/{} \;

请注意,此两阶段find解决方案不使用bashisms,并且可能可以在任何shell中运行。

答案 1 :(得分:0)

这是一个解决方案,它甚至可以正确处理不常见的文件名(比如内部有换行符的文件名等)。

首先创建目录树,然后创建空文件。除了//<p><span id="12">hello</span></p><div style="align:center">i am <span id="24">a</span><span id="40">grand</span><span id="10">mother</span></div> findmkdir之外,还需要其他外部命令。

touch

修改 删除#!/bin/bash # IMPORTANT: SOURCE and DESTINATION have to be absolute pathes # To fix the missing parameter -printf of find in mac os x, # i used a technique to reproduce the functionality. # But now it IS IMPORTANT that both of these variables contain an absolute path! SOURCE="/home/you/source_dir/" DESTINATION="/where/ever/destination_dir/" #first 'copy' the directory tree while IFS="" read -r -d '' -u 9 dir do #remove the $SOURCE part dir="${dir#${SOURCE}}" mkdir "${DESTINATION}/${dir}" done 9< <(find "${SOURCE}" -type d -print0) #then create empty files inside the new tree while IFS="" read -r -d '' -u 9 file do #remove the $SOURCE part file="${file#${SOURCE}}" touch "${DESTINATION}/${file}" done 9< <(find "${SOURCE}" -type f -print0) -printf工具的使用,因为它似乎在mac os x中不存在 - 使用bash参数替换来重新创建行为。

答案 2 :(得分:0)

您可以尝试在for循环中使用touch

cd /PATH/TO/SOURCE/FOLDER/
for f in *; 
 do touch /PATH/TO/DEST/FOLDER/$f; 
done

编辑: 上面的代码会为您提供/SOURCE/FOLDER中的所有文件和文件夹,但不会递归。 要仅为源文件创建空文件并创建目录树(所有子文件夹),您可以使用:

FILES=$(find /PATH/TO/SOURCE/FOLDER/ -type f) 
for f in $FILES; 
do touch /PATH/TO/DEST/FOLDER/$f;
done

我希望它有所帮助!