合并两个目录,保留较大的文件

时间:2016-11-01 23:24:21

标签: bash file merge directory find

考虑例如

mkdir dir1
mkdir dir2

cd dir1
echo "This file contains something" > a
touch b
echo "This file contains something" > c
echo "This file contains something" > d
touch e

cd ../dir2
touch a
echo "This file contains something" > b
echo "This file contains something" > c
echo "This file contains more data than the other file that has the same name but is in the other directory.  BlaBlaBlaBlaBlaBlaBlaBlaBla BlaBlaBlaBlaBlaBlaBlaBlaBla BlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBla. bla!" > d

我想合并dir1dir2。如果两个文件具有相同的名称,则只能保留大小最大的文件。以下是合并目录的预期内容

a # Comes from `dir1`
b # Comes from `dir2`
c # Comes from either `dir1` or `dir2`
d # Comes from `dir2`
e # Comes from `dir1`(is empty)

1 个答案:

答案 0 :(得分:1)

假设没有文件包含换行符:

find . -type f -printf '%s %p\n' \
  | sort -nr \
  | while read -r size file; do
    if ! [ -e "dest/${file#./*/}" ]; then
      cp "$file" "dest/${file#./*/}";
   done

基本上找到输出filesize path的列表,即:

221 ./dir1/a
1002 ./dir1/b
11 ./dir2/a

此列表按数字排序:

1002 ./dir1/b
221 ./dir1/a
11 ./dir2/a

然后,如果每个文件都不在dest目录中,则会复制它们。