Copy files to a destination folder only if the files already exist. but the source files have a different file extension.

i.e I have a backup of some files with ".desktop.in" extension and I want to copy to destination where the files extensions are ".desktop" and only the files that already exist in the destination.

source folder contain:

  • a.desktop.in
  • b.desktop.in
  • c.desktop.in

destination folder contain:

  • a.desktop
  • b.desktop

Want only to overwrite a.desktop and b.desktop files

Tried this:

for file in /destination/*.desktop;do cp /src/"${file##*/}".in "$file";done

But that doesn't look optimized for that task.

Do you know a better way to do that?

  • Do you have access to GNU tar?
    – Cyrus
    Mar 4, 2015 at 7:01

3 Answers 3

for file in /destination/*.desktop; do echo cp "/src/${file##*/}.in" "$file"; done

If everything looks good, remove echo.


What you have is basically as good as it gets.

You can save a tiny bit of file name manipulation by changing to the directory where you're enumerating the files. It's a matter of readability, not performance.

set -e
cd /destination
for file in *.desktop; do
  cp "/src/$file.in" "$file"

Don't forget to check for failures.


Found two ways:

for file in /src/*.desktop.in; do
  if test -e "/dest/$(basename ${file})"
    then cp "/src/${file}.in" "/dest/${file}"

rsync and --existing:

for file in /src/*.desktop.in; do 
  rsync --dry-run --existing --verbose "/src/${file}" "/dest/${file%.in}"

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .