Copy file to two folders with condition

Hello!

Please, help me write this simple script using bash scripting.

Task:

In Folder1 I have files:
name1.txt, name2.txt, name3.txt .. etc
In Folder2 may located such files:
name1.txt, name2.txt .. etc
In Folder3 may located files like:
name1.txt_abc{some_symbols}_vxz, name2.txt_abc{some_symbols}_vxz ... etc - it's the same files as in Folder1 and Folder2, only the names are different.

So, I must to copy files from Folder1 To Folder2, if the file doesn't exist in Folder2 OR Folder3.

Example:
I must to copy file name4.txt to Folder2 if Folder2 doesn't contain name4.txt OR Folder3 doesn't contain file with name like name4.txt_{something}

Thanks!

Here is an untested solution:

for file $(ls Folder1)
do
  ls Folder2/$file Folder3/$file* 1>/dev/null 2>&1
  [ $? -eq 0 ] || cp Folder1/$file Folder2/$file
done

this will help you.........

cd to $path/folder1
ls -l name*.txt > files_list
for i in `cat files_list`
do
  file_name=$i
  new_file_name='$file_name'_abc{symbol}_vxz
  cp $file_name $path/Folder2/$new_file_name
done

@ Dahu: your solution is incorrect:

ls Folder2/$file Folder3/$file*

will return non-zero even if $file exists in one of the dirs (but doesn't in the other). You are also missing keyword 'in' in the for loop.

@ rajesh_pola: The quotes around '$file_name' will prevent this variable from expanding. Besides that, you never look into Folder3, instead you hardcoded _abc{symbol}_vxz ...

How about this?

cd Folder1
for f in * ; do
   [[ -f /path/to/Folder2/$f ]] && echo "$f found in Folder2" && continue
   ls /path/to/Folder3/${f}* &> /dev/null && echo "$f found in Folder3" && continue
   cp $f /path/to/Folder2
done
1 Like

You're right, that why I said untested ;), I usually test my scripts before posting but this time I was in an hurry

try this

 
for file in Folder1/*;do 
f=$(basename $file); 
test -f Folder2/$f || cp $file Folder2/; 
test -f Folder3/${f}_SOMETHING || cp $file Folder3/${f}_SOMETHING ; 
done

thank you, friends :slight_smile: