Search code examples
bashmatchcp

CP only folders data that match in two different directories into one directory using linux or bash


What would be a efficient way to look into two different directories and if subdirectories match, copy these subfolders in a new output folder linux or bash scripting? I know I need cp command and do match based on SC#### values.

Example folder one:

[NAME]$ Project
Sample_SC1234-AAA-AAA
Sample_SC2345-AAA-BBB
Sample_SC3456-CCC-CCC
Sample_SC4567-DDD-AAA

Example folder Two:

[NAME]$ Lz
Sample_SC1234-AAA-BBB
Sample_SC4567-BBB-AAA
Sample_SC5678-DDD-BBB
Sample_SC6789-BBB-DDD

Wanted output:

[NAME]$ New
Sample_SC1234-AAA-BBB
Sample_SC4567-BBB-AAA
Sample_SC1234-AAA-AAA
Sample_SC4567-DDD-AAA

Solution

  • ls Project Lz|grep Sample_SC |cut -d '-' -f 1|sort |uniq -c |awk '{if($1 > 1)print $2}' |while read line
    do
        cp Project/$line* Lz/$line* New/
    done