Search code examples
bashcp

Bahs - How To Copy Files From A Directory To Multiple Directories?


The directory (mydir) has 1000 files (ls | wc -l) but I want to copy only those files with file.num.txt to a directory num.

Here is an example:

  1. mydir
    • file.1
    • file.1.txt
    • file.2
    • file.2.txt
    • ...
  2. /home/user1/store dir has dirs like
    • dir1
    • dir2
    • ...

So I want to copy file.1.txt to dir1, file.2.txt in dir2 and so forth.

Thanks.


Solution

  • This should work:

    #!/bin/bash
    src="mydir"
    dest="/home/user1/store"
    dir="dir" #name of the dir without number, i.e dir from dir1, dir2
    regex='(.*\.)([0-9]+)(\.txt$)'
    for file in "$src"/*;do
      if [[ -f $file ]];then
        if [[ $file =~ $regex ]];then
          mkdir -p "$dest"/"$dir${BASH_REMATCH[2]}"
          cp "$file" "$dest"/"$dir${BASH_REMATCH[2]}"
        fi
      fi
    done
    

    Explanation:

    ${BASH_REMATCH[2]} contains the captured group #2 (which is the number part of filename) from $file matched against pattern $regex. The pattern matching is done in the if statement:

    if [[ $file =~ $regex ]];then
    

    mkdir -p is used in case the directory structure doesn't exist, it will create it.