问题
I want to copy some files from directory A to directory B on basis of partial filenames which are in a text file.
I tried the command below, but it's not working
for fn in $(cat filename.txt); do find . -type -f -name '$fn*' \
-exec rsync -aR '{}' /tmp/test2 \;
File names are in format abcd-1234-opi.txt, rety-4567-yuui.txt. I have to grep numbers from file names and then copy those files to another folder, I have numbers in a text file.
Can anybody guide me?
回答1:
If I understand your question correct:
for file in $(<./example); do cp "${file}" /tmp/test2/; done
for file in $(<./example); do find . -type f -name ${file} -exec rsync -aR {} /tmp/test2/ \; ; done
回答2:
If understand correctly, the pattern to search for is the first 3 digits of the numbers after the first -, like this:
abd-12312-xyz ^^^ 88-45644-oio ^^^ qwe-78908-678 ^^^
Here's one way to write that:
while read line; do
pattern=${line#*-}
pattern=${pattern:0:3}
find . -type f -name "*$pattern*" -exec rsync -aR {} /tmp/test2 \;
done < patterns.txt
If your inputs are like "veeram_20171004-104805_APOLLO_9004060859-all.txt", and you want to extract the "9004060859", then you can try to find a different logic to extract that. For example, "cut off every after the last '-', and everything before the last '_'". You can write like this:
pattern=${line%-*}
pattern=${pattern##*_}
回答3:
Running find repeatedly should probably be avoided. Instead, factor the expressions into the find command line programmatically.
awk 'BEGIN { printf "find . -type -f \\("; sep="" }
{ printf "%s -name \047*%s*\047", sep, $0; sep=" -o" }
END { printf " \\) -exec rsync -aR '{}' /tmp/test2 \\;\n" }' filename.txt |
sh
Leave off the pipe to sh to test.
来源:https://stackoverflow.com/questions/47462385/copy-or-move-files-to-another-directory-based-on-partial-names-in-a-text-file