2

I'd like to copy the files searched using find command into the current directory. I am executing the following command-line:

    # find linux books
$ find ~ -type f -iregex '.*linux.*\.pdf' -print0 | xargs -0 echo
    # Expected output on STDOUT
../Books/LinuxCollection/Linux_TLCL-17.10.pdf ../Richard Blum, Christine Bresnahan - Linux Command Line and Shell Scripting Bible, 3rd Edition - 2015.pdf ..

I wish to copy the files to the current directory using the cp command. Here is the command that I entered:

$ find ~ -type f -iregex '.*linux.*\.pdf' -print0 | xargs -0 cp .

However, I get an error as shown below upon executing the above command:

usage: cp [-R [-H | -L | -P]] [-fi | -n] [-apvXc] source_file target_file
       cp [-R [-H | -L | -P]] [-fi | -n] [-apvXc] source_file ... target_directory

I have also tried to resolve the issue by using command substitution. Here is the command that I tried:

$ cp $(find ~ -type f -iregex '.*linux.*\.pdf' -print0) .

However, I get another error as shown below upon executing the above command:

cp: Blum,: No such file or directory

How do I accomplish the desired result using the xargs command?

2

xargs appends its input to the command, so you are basically running cp . source_file. Use

find ~ -type f -iregex '.*linux.*\.pdf' -print0 | xargs -I '{}' -0 cp '{}' .

instead.

  • Thank you. I refer the manual page to the magic option I. Honestly very confused about its descritption. – Algebra Mar 28 '18 at 6:55
  • -I is just used to define the character(s) to be replaced by the input afterwards. So xargs reads from stdin and then takes whatever it read and puts it where the {} is. – nohillside Mar 28 '18 at 6:58
1

You can also accomplish the desired result easily without using xargs command as shown below:

find ~ -type f -iregex '.*linux.*\.pdf' -print0 -exec cp {} . \;

Makes up for a simpler command line and doesn't involve piping.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .