Macos – How to use sed to alter the results of find and pass the results to cp

findmacossedsolaris

In solaris, I'd like to copy all files found by the find command to a slightly different path. The following script basically executes cp for each file found by find. For example:

cp ./content/english/activity1_compressed.swf ./content/spanish/activity1_compressed.swf
cp ./content/english/activity2_compressed.swf ./content/spanish/activity2_compressed.swf
...

#!/bin/bash

# Read all file names into an array
FilesArray=($(find "." -name "*_compressed.swf"))

# Get length of an array
FilesIndex=${#FilesArray[@]}

# Copy each file from english to spanish folder
# Ex: cp ./english/activity_compressed.swf ./spanish/activity_compressed.swf
for (( i=0; i<${FilesIndex}; i++ ));
do
    source="${FilesArray[$i]}"

    # Replace "english" with "spanish" in path  
    destination="$(echo "${source}" | sed 's/english/spanish/')"

    cp "${source}" "${destination}"
done

exit 0;

It seems like a bit much and I wonder how to use sed in-line with the find and cp commands to achieve the same thing. I would have hoped for something like the following, but apparently parentheses aren't acceptable method of changing order of operation:

find . -name *_compressed -exec cp {} (echo '{}' | sed 's/english/spanish/')

Best Answer

There are easier ways, but for portability sake we can use a bit of forking and backticks:

find . -name *_compressed -exec sh -c 'cp {} `echo {} | sed 's/english/spanish/'`' \;
Related Question