Compare the file names in two directories

时间:2019-04-08 13:48:40

标签: linux bash

I have to create a bash script that compares content by file names in two directories, for example "First_Directory" contains file with name "123456" therefore "Second_Directory" should also contain "_file_123456.png".
If the "Second_Directory" doesn't contain exact number in the file name from the "First_Directory", then copy a "dummy.png" file from the "Third_Directory" to the "Second_Directory" and rename it according to example: "_file_[First_Directory_File_Name].png"

Path:
/path/to/directory/First_Directory/Second_Directory/
/home/username/Third_Directory/dummy.png

First_Directory content:
123456
789012
345678

Second_Directory content:
_file_123456.png
_file_789012.png
_file_345678.png

DIR1=/path/to/directory/First_Directory/
DIR2=/path/to/directory/First_Directory/Second_Directory/
PNG=/home/username/Third_Directory/dummy.png

DIFF=$(diff <(find $DIR1 -maxdepth 1 -type f -name "*" -printf '%f\n') <(find $DIR2 -type f -name '_file_*.png' -printf '%f\n'))

if [ "$DIFF" ];
then
   cp $PNG $DIR2
fi

My script only displays difference between these two directories. I couldn't find a solution on how to compare only specific part of the file name. It also should copy and rename a file in the "Second_Directory" as I mentioned in the description.

2 个答案:

答案 0 :(得分:3)

在第一个目录上循环将是正确的解决方案。对于更新的要求,您可以先找到基本目录并循环。

for DIR1 in `find . -name First_Directory_*`
do
   DIR2="$DIR1"/Second_Directory
   PNG=/path/to/dummy.png
   for file in "$DIR1"/*
   do
     if [ -f "$file" ]; then
        dir2_file="$DIR2"/_file_${file##*/}.png
        if [ ! -f "$dir2_file" ]; then
           cp "$PNG" "$dir2_file"
        fi
     fi
   done
done

答案 1 :(得分:0)

您可以通过for循环遍历第一个目录中的所有文件:

let foo = 'foo';
let arr = ['a', 'b'];
let bar = [];
a = foo;
typeof a == 'string' ? bar = [a] : bar = [...a];
console.log(bar);

请勿对非系统变量使用大写的变量名,以免发生冲突。