-3

How can I make two directories with some file in them, and copy the file between them?

If those files have the same name then an error should be thrown.

aliceinpalth
  • 1,613
  • cp -i will prompt you before overwriting – Raman Sailopal Jan 31 '18 at 16:11
  • 1
    If you copy one file between the two directories without renaming the file in the process, then the copy will have the same name as the original and there should be an error? This question is unclear. – Kusalananda Jan 31 '18 at 16:57

3 Answers3

-1

Without error notification:

mkdir test1 test2
cp --no-clobber test1/* test2/
cp --no-clobber test2/* test1/
Garstlig
  • 116
-1

With error notification:

mkdir test1 test2
for i in `ls test1/`; do
  if [ ! -e "test2/$i" ] ; then cp "test1/$i" test2/
  else echo "ERROR: test2/$i already exists" >&2
  fi
done
for i in `ls test2/`; do
  if [ ! -e "test1/$i" ] ; then cp "test2/$i" test1/
  else echo "ERROR: test1/$i already exists" >&2
  fi
done
Garstlig
  • 116
-2

Take the list of files from 2 both directories and save it in 2 files

Directory1_files.txt,Directory2_files.txt.

Let us assume you need to copy the files from Directory1 to Directory2. It should copy only the files from Directory 1 which is not present in Directory 2

find First_directory_path -maxdepth 1 -type f  | awk -F "/" '{print $NF}' > Directory1_files.txt

find Second_directory_path -maxdepth 1 -type f  | awk -F "/" '{print $NF}' > Directory2_files.txt


awk 'NR==FNR {a[$1];next}!($1 in a) {print $1}' Directory2_files.txt Directory1_files.txt >Files_need_to_copy_to_directory_2

awk '{print "cp" " " "directory1path/"$1 " " "directory2path"}' Files_need_to_copy_to_directory_2| sh