Grep command allows us to filter the content from the input which matches the pattern. Here we are going to use combination of three commands including grep, to copy / move the files recursively to another directory which matches our pattern.

So here i listed three commands we are going to use:
     1) ls – To list the files in certain location
     2) grep – To filter the output of  “ls” command to match our pattern
     3) xargs – To pass output of grep command as an argument (input) to copy command

Lets see the command in action:
ls '/home/john/test/'  | grep 'db_backup_*' | xargs cp -rfpv /home/john/old/.

Above we listed the files located in ‘/home/john/test’ then we used grep command to select only files which has “db_backup_”  in the file name. Next we copy those filtered files list by passing as an argument (input) to copy command (cp) using xargs.

 |  - This pipe (Vertical bar) is used to combine multiple commands to run one by one.

We have used some options in “cp” command, lets see what is it.

r – Recursive. Tells the command to copy files recursively
f – Force copy by removing the destination file if required.
p – Retain the same file privileges
v – Visualize the process (Each file displayed on screen when copied)

Like this you can copy multiple files having similar names to another directory recursively using grep command.

Comments (1)
  1. Image
    Md - Reply

    March 04, 2020

    When I write a similar line, but with "xargs mv dest" , it seems to interpret dest as the source. How do I make the xarg cmd feed into the source operand?

Leave a Comment

loader Posting your comment...