我有三个目录。我想比较directory1和directory2,然后将那些更改/新文件复制到directory3中。是否有一种简单的方法来做到这一点,也许可以使用linux diff和cp命令?我愿意听取建议。
谢谢!
安德鲁
谢谢!
安德鲁
根据您的描述,我相信这就是您想要的。
for file in dir2/*; do
file_in_dir1=dir1/$(basename ${file})
if [ ! -e ${file_in_dir1} ]; then
# If the file in dir2 does not exist in dir1, copy
cp ${file} dir3
elif ! diff ${file} ${file_in_dir1}; then
# if the file in dir2 is different then the one in dir1, copy
cp ${file} dir3
fi
done
有一件事我不确定的是,如果一个文件存在于dir1但不存在于dir2中,你想要什么。
这个yonder线程应该可以很好地解决你的问题!
从那里复制:
#!/bin/bash
# setup folders for our different stages
DIST=/var/www/localhost/htdocs/dist/
DIST_OLD=/var/www/localhost/htdocs/dist_old/
DIST_UPGRADE=/var/www/localhost/htdocs/dist_upgrade/
cd $DIST
list=`find . -type f`
for a in $list; do
if [ ! -f "$DIST_OLD$a" ]; then
cp --parents $a $DIST_UPGRADE
continue
fi
diff $a $DIST_OLD$a > /dev/null
if [[ "$?" == "1" ]]; then
# File exists but is different so copy changed file
cp --parents $a $DIST_UPGRADE
fi
done
diff -qr ./dir1 ./dir2 | sed -e 's/^Only in\(.*\): \(.*\)/\1\/\2/g' -e 's/ and \..*differ$//g' -e 's/^Files //g' | xargs -I '{}' cp -Rf --parents '{}' ./dir3/
这种解决方案使用sed从diff命令中删除所有附加文本,然后复制文件并保留目录结构。#!/bin/bash
# setup folders for our different stages
DIST=/var/www/localhost/htdocs/dist/
DIST_OLD=/var/www/localhost/htdocs/dist_old/
DIST_UPGRADE=/var/www/localhost/htdocs/dist_upgrade/
cd $DIST
find . -type f | while read filename
do
newfile=false
modified=false
if [ ! -e "$DIST_OLD$filename" ]; then
newfile=true
echo "ADD $filename"
elif ! cmp $filename $DIST_OLD$filename &>/dev/null; then
modified=true
echo "MOD $filename"
fi
if $newfile || $modified; then
#massage the filepath to not include leading ./
filepath=$DIST_UPGRADE$(echo $filename | cut -c3-)
#create folder for it if it doesnt exist
destfolder=$(echo $filepath | sed -e 's/\/[^\/]*$/\//')
mkdir -p $destfolder
#copy new/modified file to the upgrade folder
cp $filename $filepath
fi
done
假设您在同一级别上有dir1
、dir2
和dir3
,其内容设置如下:
mkdir dir1
mkdir dir2
echo 1 > dir1/a
echo 1 > dir2/a
echo 2 > dir1/b
echo 3 > dir2/b
echo 4 > dir2/c
cp -r dir1 dir3
当您创建并应用补丁时:
diff -ruN dir1 dir2 | patch -p1 -d dir3
接下来你会看到 dir2
和 dir3
内容相同的部分。
如果你的 dir2
不在与 dir1
同一级别的位置上,
那么你就需要编辑补丁里的文件名,
使得在dir1
和dir2
中的文件名拥有相同数量的路径组件。
最好将你的dir2
放置在与dir1
相同的级别上,
因为我至少不知道有其他更优雅的方法可以解决这个问题。
以下是一种“丑陋”的方法。
假设你的dir2
位于某个$ BASEDIR
中,
那么你应该更新你的差异,从 dir2
的路径中删除 $ BASEDIR
,
如下所示:
diff -ruN dir1 $BASEDIR/dir2 | \
perl -slne 'BEGIN {$base =~ s/\//\\\//g; print $base}
s/\+\+\+ $base\//\+\+\+ /g; print' \
-- -base=$BASEDIR
然后你可以像上面那样应用生成的路径。