1

Considering folderA containing those files:

foo bar baz 

and folderB containing those:

foo baz foobar qux 

How can I copy foo and baz from folderA to a new folderC?
Note that I'm comparing only their names, not their contents.

2 Answers 2

2

Use a for loop over the files. Parameter expansion can be used to extract parts of the path:

#! /bin/bash for file in folderA/* ; do basename=${file##*/} if [[ -f folderB/$basename ]] ; then cp "$file" folderC/"$basename" fi done 

You can loop over files in folderB, too, and I'd recommend it if folderB contains significantly fewer files than folderA.

1

This works in my bash:

echo "Folder A" ls -l ./foldera/ echo "Folder B" ls -l ./folderb/ echo "Folder C" ls -l ./folderc/ read -p "Press any key to start" duplicates=( "$(find foldera folderb -type f -exec basename {} \; |sort |uniq -d)" ) for file in ${duplicates[@]}; do cp "./foldera/$file" "./folderc/$file" done echo "Script Finish. Folder C" ls -l ./folderc/ 

Output:

root@debian:# ./bashtest.sh Folder A total 32 -rw-r--r-- 1 root root 8230 Oct 14 01:36 abp.png -rwxr-xr-x 1 root root 8805 Dec 9 01:58 appslist.sh -rwxrwxrwx 1 root root 2682 Nov 14 02:50 cpu.sh -rw-r--r-- 1 root root 898 Oct 11 00:25 tkinter-3.py Folder B total 24 -rw-r--r-- 1 root root 8230 Oct 14 01:36 abp.png -rw-r--r-- 1 root root 898 Oct 11 00:25 tkinter-3.py -rwxr-xr-x 1 root root 595 Oct 28 00:02 yadlist.sh -rwxr-xr-x 1 root root 2455 Nov 16 01:24 yadnotebook.sh Folder C total 0 Press any key to start Script Finish. Folder C total 16 -rw-r--r-- 1 root root 8230 Dec 18 23:55 abp.png -rw-r--r-- 1 root root 898 Dec 18 23:55 tkinter-3.py 
1
  • @Patrick Answer tested and updated. Previous answer was wrong. Sorry. Commented Dec 18, 2016 at 21:59

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.