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:
- mydir
- file.1
- file.1.txt
- file.2
- file.2.txt
- ...
- /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.
This should work:
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:mkdir -p
is used in case the directory structure doesn't exist, it will create it.