如何使用 shell 脚本比较两个文件夹并将差异复制到第三个文件夹

如何使用 shell 脚本比较两个文件夹并将差异复制到第三个文件夹
#!/bin/sh
# This is comment!
echo Hello World
for file1 in /C:/Users/shubham.tomar/Desktop/Shell/Test1/*; 
do
filename1=$(basename "$file1")
echo $filename1
echo "------------------------"
for file2 in /C:/Users/shubham.tomar/Desktop/Shell/Test2/*;
do
filename2=$(basename "$file2")
echo $filename2
if [["filename1" = "filename2"]]; then
echo "---File matched---"
else
mv -f /C:/Users/shubham.tomar/Desktop/Shell/Test2/$filename2 /C:/Users/shubham.tomar/Desktop/Shell/Moved/
fi
echo "--------------File Moved-----------"
done
done

**

关于问题的注释

**

在 ex 的特定路径中有一些文件:Desktop/Test1 和 Downloads/Test2 我想编写一个 shell 脚本,将 Test2 中而不是 Test1 中存在的所有文件移动到 ex 的路径:Documents/MovedFiles 文件可能是任何类型

答案1

sf() {
    # find all files in the directory $1 non-recursively and sort them
    find $1 -maxdepth 1 -type f printf '%f\n' | sort
}

然后运行

join -v 1 <(sf Tes2) <(sf Tes1) | xargs -d '\n' -I file mv Tes2/file MovedFiles/

管道的左操作数查找Tes2该目录中不存在的所有文件Tes1

然后管道的右操作数将这些文件移动到目录中MovedFiles

答案2

使用嵌套的 for 循环是错误的。您不想将Test1中的每个文件名与Test2.

编辑:一些用于调试和避免使用 file 的附加脚本行*

#!/bin/sh

# Check if this is correct
dir1="/C:/Users/shubham.tomar/Desktop/Shell/Test1"
# maybe you have to write
# dir1="/c/Users/shubham.tomar/Desktop/Shell/Test1"
dir2="/C:/Users/shubham.tomar/Desktop/Shell/Test2"
targetdir="/C:/Users/shubham.tomar/Desktop/Shell/Moved"

# for debugging
echo contents of dir1 $dir1
ls "$dir1"
echo contents of dir2 $dir2
ls "$dir2"

# loop over all files in $dir2 because you want to find files in $dir2 that are not in $dir1
for file2 in "$dir2"/*
do
    # if $dir2 does not exist or is empty we will get something like file2="/C:/Users/shubham.tomar/Desktop/Shell/Test2/*" 
    # That's why check if the file exists
    if [ -f "$file2" ]
    then
        filename2=$(basename "$file2")
        echo $filename2
        echo "------------------------"

        # does a file with the same basename exist in $dir1?
        if [ ! -f "$dir1/$filename2" ]
        then
            # using "$targetdir"/." makes sure you get an error if $targetdir is a file instead of a directory
            mv -f "$file2" "$targetdir"/.
            echo "--------------File Moved-----------"
        else
            echo "file with the same name exists in $dir1"
        fi
    fi
done

如果您想先尝试此操作而不实际移动文件,您可以替换该行

        mv -f "$file2" "$targetdir"/.

        echo mv -f "$file2" "$targetdir"/.

相关内容