Skip to content
Advertisement

Copy first N files which start with ‘a’ ‘c’ or ‘e’ from one folder to another in Linux

I have many files in specified directory. For instance, I want to copy 6 of them to one location. I came up with this:

find . -type f |head -6| xargs cp /specified_dir/[ace]* -t /target_loc

The problem is that every file which starts with ‘a’ ‘c’ ‘e’ is copied. There should be first 6 files, but I receive 8 (4 with ‘a’, 3 with ‘c’ and 1 with ‘e’). I was wondering, if there is a way to fix this.

Advertisement

Answer

With your command you get only the 6 first results from find (which are not the files starting with [ace]) but what you finally execute is this command:

cp /specified_dir/[ace]* -t /target_loc <file_argument>

which copies all the [ace]* files plus the <file_argument> provided through xargs to target location. And you execute this command 6 times.


What you want is first to find the [ace]* files, to get the first 6 of them (as you do with head) and to write the last command without the file to be copied, this argument will be provided from xargs.
find . -type f -name "[ace]*" | head -6 | xargs cp -t /target_loc

Now this was wrong or at least not safe, as will not handle for example filenames with spaces. So you can use this syntax:

find . -type f -name "[ace]*" | head -6 | xargs -I{} cp {} -t /target_loc

-I sets the replacement string so when this exists later, it means position of a quoted argument.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement