uncommon_currency
uncommon_currency

Reputation: 11

BASH: move files according to dirname

I would like to move a number of processed files from their raw directory to a new directory. Each directory name corresponds, but only by two numbers; the rest of the dir names are different. How can I define a pattern within a for-loop to easily find and move these files to and from their corresponding dirs?

More details: I have two sets of 90 directories. The first set contains raw files, and the second is where I’d like to move corresponding gzipped files. The problem is that the first and second sets of directories only share one part of their name: the first is ABC_1##; the second is ##YY00ZZ (ex: raw dir ABC_123 corresponds to new dir 23yy00zz. There is a complicated but necessary reason that they have to follow this format). The gzipped files are all given the same name (let’s call it FILE.gz), but crucially must go from raw dir 23 to new dir 23…

This is what I have tried, and it is not working for me (using cp instead of mv so as to avoid messing up too much):

for dir in $(ls -d ~/path/to/raw/ABC_1{01..90}/EACH_RAW_DIR); do
    dir2=$(ls -d ~/path/to/new/{01..90}yy00zz/EACH_NEW_DIR)
    echo $dir
    echo $dir2
    cp -r $dir/FILE.gz $dir2/.
done

Thanks for any insight!

Upvotes: 1

Views: 159

Answers (2)

janos
janos

Reputation: 124646

You can use a range of {101..190} and chop off the first digit as needed:

for i in {101..190}; do
      cp ~/path_to_raw_dir/ABC_$i/file.gz ~/path_to_new_dir/${i:1}yy00zz/file.gz
done

Upvotes: 1

Ashutosh Bharti
Ashutosh Bharti

Reputation: 367

shell expansion won't expand {01..90} with padded zeros. It would expand it as 1,2,3,...,11,12,...,90. Better to do it in two steps: 1) first ABC_10{1..9} 2) ABC_1{10..90}

or you can use seq -w 90

Once you have taken care of that, you only need to copy like this:

for i in "$(seq -w 90)"; do
      cp ~/path_to_raw_dir/ABC_1"$i"/file.gz ~/path_to_new_dir/"$i"yy00zz/file.gz
done

Upvotes: 1

Related Questions