You can do that with a somewhat complex awk
command:
timp@helez:~/tmp/cp_find_test$ ls
command.sh command.sh~ test.1 test.2 test.3
timp@helez:~/tmp/cp_find_test$ cat test.1
Aventura
Whatever
Florida
timp@helez:~/tmp/cp_find_test$ cat test.2
Random stuff
Floridaasdklfj
timp@helez:~/tmp/cp_find_test$ cat test.3
FL
timp@helez:~/tmp/cp_find_test$ ./command.sh
cp -rf ./test.3 /pathtofolder/keywords/FL
cp -rf ./command.sh /pathtofolder/keywords/Florida
cp -rf ./test.1 /pathtofolder/keywords/Aventura
cp -rf ./command.sh~ /pathtofolder/keywords/Florida
timp@helez:~/tmp/cp_find_test$ cat command.sh
KEYWORDS=("Florida" "FL" "Miami-Dade" "Aventura" "Bal Harbour" "Bay Harbor Islands")
IFS=$'\n'
find . -size +1c -type f ! -exec grep -oHwF "${KEYWORDS[*]}" {} \; | awk 'BEGIN {FS=":"; last_line=""} {if (last_line!=$1) {print "cp -rf", $1, "/pathtofolder/keywords/"$2}; last_line=$1}'
I added a -o
to your grep
so that it would only print the matching parts of the line, and then used awk
to build the cp
commands.
The reason I didn't use -m 1
in grep
instead of the if (last_line!=$1) {...}; last_line=$1
was because if there's multiple matches on the same line it would print them all out as separate lines:
timp@helez:~/tmp/cp_find_test$ ./command.sh
cp -rf ./test.3 /pathtofolder/keywords/FL
cp -rf ./command.sh /pathtofolder/keywords/Florida
cp -rf ./command.sh /pathtofolder/keywords/FL
cp -rf ./command.sh /pathtofolder/keywords/Miami-Dade
cp -rf ./command.sh /pathtofolder/keywords/Aventura
cp -rf ./command.sh /pathtofolder/keywords/Bal Harbour
cp -rf ./command.sh /pathtofolder/keywords/Bay Harbor Islands
cp -rf ./test.1 /pathtofolder/keywords/Aventura
cp -rf ./command.sh~ /pathtofolder/keywords/Florida
cp -rf ./command.sh~ /pathtofolder/keywords/FL
cp -rf ./command.sh~ /pathtofolder/keywords/Miami-Dade
cp -rf ./command.sh~ /pathtofolder/keywords/Aventura
cp -rf ./command.sh~ /pathtofolder/keywords/Bal Harbour
cp -rf ./command.sh~ /pathtofolder/keywords/Bay Harbor Islands
timp@helez:~/tmp/cp_find_test$ cat command.sh
KEYWORDS=("Florida" "FL" "Miami-Dade" "Aventura" "Bal Harbour" "Bay Harbor Islands")
IFS=$'\n'
#find . -size +1c -type f ! -exec grep -oHwF "${KEYWORDS[*]}" {} \; | awk 'BEGIN {FS=":"; last_line=""} {if (last_line!=$1) {print "cp -rf", $1, "/pathtofolder/keywords/"$2}; last_line=$1}'
find . -size +1c -type f ! -exec grep -m 1 -oHwF "${KEYWORDS[*]}" {} \; | awk 'BEGIN {FS=":"} {print "cp -rf", $1, "/pathtofolder/keywords/"$2}'