Reputation: 113
My list.txt
file has a few hundred entries pointing to filenames laying on the /tmp
partition. I'm collecting files that start with "a" such as apples.txt
, andromeda.txt
, etc to copy them into a directory.
However, I do not want to copy all the files but only the first file found. It doesn't have to be sorted; just the first one.
How do I do that? Any tips are welcome.
#!/bin/bash
for i in `/usr/bin/cat /tmp/list.txt`
do
find /tmp/$i -name a* -exec cp {} /tmp/found_first_file_start_with_a \;
done
Upvotes: 0
Views: 308
Reputation: 377
Forget find
, try this:
set -- /tmp/a*
test -z "$1" || cp "$1" /tmp/found_first_file_start_with_a
Upvotes: 1
Reputation: 126378
You can use the -quit
command to find
to get it to stop after the first one:
find /tmp -name a* -exec cp {} /tmp/found_first_file_start_with_a \; -quit
however, this will only quit if the exec returns true. If the cp command fails (for whatever reason), it will continue searching for more files. So you can instead just print the first file and capture it for a separate cp
command:
file=$(find /tmp -name a* -print -quit)
cp $file /tmp/found_first_file_start_with_a
Upvotes: 0