add-semi-colons
add-semi-colons

Reputation: 18800

Bash Shell Script to iterate over folders within folder and copy files

I want to iterate over multiple directories within a directory and copy a specific csv file to different location. My shell script knowledge is at a starter level. I found couple of solutions similar to what I am thinking of doing, but the problem is in my case sub directory name is not same.

Here is the structure: I have root directory ~/2013-03-03/

Then I have following directories, I have only put few, but I have close to 300 sub directories.

ab   bar      ch   eml      gn   iu   kv       mhr     ne   pfl       sc   sw   ug                   zea
ace  bat-smg  chr  ext      got  jbo  kw       mi      nov  pi        scn  szl  ur                   zh-classical
af   bcl      chy  ff       gu   kaa  ky       ml      nrm  pih       sco  tet  ve                   zh-min-nan
ak   bh       ckb  fiu-vro  gv   kab  lad      mn      nso  pnb       sd   tg   vec                  zh-yue
als  bi       co   fj       ha   kbd  lbe      mo      nv   pnt       se   ti   vep 

Each of these directories have hundred(s) of csv files where the csvfile name starts with the name of the directory. But I am only interest in one specific csv file. Assume that name is mycsvfile.csv. I want to copy this file from each subdir to a different directory in ~/2013-03-03/new_dir

Upvotes: 0

Views: 756

Answers (2)

Wrikken
Wrikken

Reputation: 70460

find ~/2013-03-03/ -name 'mycsvfile.csv' -exec cp {} ~/2013-03-03/new_dir/ \;

If the files are named subfoldername/subfoldername-mycsvfile.csv, use something like:

find ~/2013-03-03/ -regextype posix-awk -regex '.*/([^/]*)/\1-mycsvfile.csv' -exec cp {} ~/2013-03-03/new_dir/ \;

... I always struggle what flavor regex can do what and how, this seems to work

Upvotes: 4

twalberg
twalberg

Reputation: 62369

There's probably many ways to accomplish that. Here's one relatively simple one:

cd ~/2013-03-03
/bin/ls -1 */mycsvfile.csv | cpio -dump ~/2013-03-03/new_dir/.

Upvotes: 2

Related Questions