Copy folder or file using the result of ls command
Situation
If you want to copy the list of files or folders using outputs of the ls command, you may find this post is useful. One simple bash command line can save your time.
Example
You might need to copy all the mp4 files in a directory to another directory. Here is an example folder structure.
/a/video1.mp4
/a/video2.mp4
/a/video3.mp4
How can we copy those mp4 files to directory b?
cp `ls /a | grep "*.mp4" | perl -ne 'print "/a/$_"'` /b
That’s it. All done! Here is the general form of the command.
cp -R `ls /path/to/source | grep -E "target" | perl -ne 'print "/path/to/source/$_"'` ./
Backtick
Inside of the command between backtick will be evaluated by the shell before the main command. Article
grep with E option
The E option escape certain special characters for example, ‘{‘ or ‘(‘. Article
perl with -ne option
The “perl” command uses the Perl programming language.
-n: causes perl to assume the following loop around your script,
-e: maybe used to enter one line of script.
Here is the article about Perl options.
Hene, the command line prints the output of the filename concatenated with the absolute path. I use the perl command to concatenate the original absolute path. Article
Leave a comment