Copy the first n files from one directory to another
Solution 1:
You need the -J
option with xargs
.
find . -maxdepth 1 -type f | head -n5 | xargs -J X cp X /target/directory
The J
option places all the filenames into the placeholder X, which can be any character(s) and cp
accepts multiple files to a target directory. It can be visualized as-
cp file1 file2 file3 file4 file5 DESTINATION
EDIT:
To handle filenames with spaces, we have tr
translate the newline character to the null character after each filename and then have xargs handle the null bit as a separator for the filenames.
find . -maxdepth 1 -type f | head -n5 | tr '\n' '\0' | xargs -0 -J X cp -- X /target/directory
Solution 2:
I found a different solution without xargs
or -exec
but I think fd0's answer is a better way to go:
while IFS= read -r f; do cp "$f" "/target/directory/"; done < <(find . -maxdepth 1 -type f | head -n5)