0

For a set of directories with similar names at different location,

/foldX/dirA with sub-directories aa1 aa2 aa3 aa4 aa5

/foldZ/dirA with sub-directories aa1 aa2 aa3

/foldY/dirA with sub-directories aa1 aa2 aa3

What could be an efficient way to copy or move the directories aa* to another folder, /foldNew/dirA, as aa1, aa2, aa3, aa4, aa5, aa6, aa7, aa8, aa9, aa10 ?

aa1 to aa4 from foldX

aa5 to aa7 from foldY

aa8 to aa10 from foldZ

1
  • Not sure what you're asking. Do you want to merge contents of similarly named directories or not? What do you mean by "efficient"? Commented Mar 19, 2015 at 21:00

1 Answer 1

0

The following script does what you want:

#!/bin/bash
counter=0
mkdir foldNew
for i in fold?/dirA/aa*; do
    counter=$((counter + 1))
    mv $i foldNew/aa$counter
done

It keeps count of how many folders it moved already, and it uses Bash's wildcard system to iterate over all the folders you want to move.

I tested it with the setup you described, and it did what you wanted, with the only exception that it moved them to aa1 through aa11, because dirA has five subdirectories, not four.

That script moves aa20 earlier than aa3. If the order of the subdirectories really matters, you can try this code:

#!/bin/bash
counter=0
mkdir foldNew
for i in $(echo fold?/dirA/aa* | sort -V); do
    counter=$((counter + 1))
    mv $i foldNew/aa$counter
done

I think that it doesn't handle spaces and newlines in filenames well, however, so be careful if you use it.

5
  • thanks. can you chek wheter this will work if number of directories are more than 9? e.g. 'aa1, aa2, ... aa15'. I tried but it seems after taking 9 directories from foldX, its switching to foldY Commented Mar 19, 2015 at 21:30
  • Replacing ? by * should work. "?" matches one character, "*" can match multiple. I'll change it. Commented Mar 19, 2015 at 21:32
  • Thank you. Further, as I expected (learning from my past codes), for more than 10 subdirectories, e.g 20, the code copies or moves /foldA/aa10 as /foldNew/aa2 This may be because when it seach for subdirectories inside foldA/DirA, it read them as aa1, aa10, aa11, ...aa19, aa2, aa20, aa3, aa4....aa9 any thought on how to overcome this? Commented Mar 19, 2015 at 21:44
  • sort -V is capable of that kind of sorting. I added an alternative script. It might do weird things when there are spaces in the filenames, so watch out. Commented Mar 19, 2015 at 21:56
  • Thanks ! But, it seems sort -V is not helping out here. Commented Mar 19, 2015 at 22:32

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.