overwrite only if both files are the same size

Dear users,

I've been looking for a way to overwrite files only if both have the same size, how could I do this? any help is very appreciated.

Best regards,

Gery

This is one method to determine if two files have the same size and then act upon it:

fs1=`wc -c test1`
fs1="${fs1##+([[:space:]])}"
fs1=`echo $fs1 | cut -d ' ' -f1`

fs2=`wc -c test2`
fs2="${fs2##+([[:space:]])}"
fs2=`echo $fs2 | cut -d ' ' -f1`

if ((fs1 != fs2)) then
  echo "files are not equal in size"
else
  echo "files are equal in size"
fi
1 Like

Thanks spacebar, nice trick, I'll try that :b:

If available on your system; stat --printf %s filename
will give you the size as recorded in the directory without opening and counting the file's contents.

1 Like

Agreed, RudiC. stat or even ls would be more efficient (much more so if the file's are large) than reading every byte.

Regards,
Alister

Not knowing what your system is, and what options stat offers, this would do the job running stat only once:

if [  $(( $(stat --printf "%s - " new  old) 0 )) -eq 0 ]; then echo "equal"; else echo "NOT equal"; fi