You need to log in to create posts and topics.

How to Copy Files Matching Names from One Folder to Another?

Is it possible to copy the files matching "Name" or "Strings" with the text file from one folder to another folder in Linux?

The answer is Yes. Let us consider an example for the above question,

Source Directory:

  • Text.ABC.0001.txt
  • Text.ABC.0002.txt
  • Text.ABC.0003.txt
  • File.ABC.0004.txt
  • File.ABC.0005.txt

The Sample Text file contains:


  • Text.ABC.0001
  • Text.ABC.0002

Now you need to copy the files which match with the string in the sample.txt file.

Which means,

Source Directory:

  • Text.ABC.0001.txt
  • Text.ABC.0002.txt

How to Do?

There are 3 ways to do and they are:

Way 1:


You can use the GREP -f command to match the strings with the sample.txt for patterns.

for i in source_dir/*.txtdo
if grep -Fq -f sample.txt <<< "$i"; then
mv -t dest_dir "$i"

Then run the below command:

$ ls
dest_dir source_dir sample.txt

Command Explanations:

  • -F Interpret patterns as fixed strings, not regular expressions.
  • -q Do not write anything to stdout.
  • -f Obtain patterns from FILE, one per line.
    Here strings:
  • <<< A variant of here documents, does variable expansion before sending the string.
    mv options:
  • -t Move all source arguments into -t directory.

Way 2:


while read line ; do
mv source_dir/${line}.ABC.0001.txt destination_dir/
done < sample.txt

The most simple command to do!

Way 3:


find source -type f | while read file; do name=$(basename $file); grep ${} sample.txt && mv -v $file dest; done

That's it. The above commands will help you to copy the files from one folder to another folder that matches the string in the text file. Comment us below.