开发者

Bash script for iterating through defined set of file names and performing commands

开发者 https://www.devze.com 2023-01-27 20:54 出处:网络
I have a set of folders named for example 10, 12, 13, 14, 18, 24 etc. They don\'t change numbers in any standard increment. I then need to move repetitively into the folders and then into the next one

I have a set of folders named for example 10, 12, 13, 14, 18, 24 etc. They don't change numbers in any standard increment. I then need to move repetitively into the folders and then into the next one to perform SVN commands which are the same ex开发者_开发百科cept for some variable extension, e.g.:

/home/boy$ cp /home/files/*Session10.* . ; svn add *Session10.*; svn commit; cd ..; cd 12;

Then the next command is analogous:

/home/boy$ cp /home/files/*Session12.* . ; svn add *Session12.*; svn commit; cd ..; cd 14;

So there should be an array or list defined, and then a for loop through that list, and then a variable whose name is expanded to be fed into the cp and svn command. Any thoughts? I hope that it can be done in the command prompt rather than in a bash script file.


The no brainer way is:

for dir in [0-9][0-9]/; do
    cd "$dir"
    cp /home/files/*Session${dir%/}.* .
    svn add *Session${dir%/}.*
    svn commit
    cd ..
done

This will only iterate over directories which are composed of 2 digits.


If the list is predefined and you're not iterating over every directory that exists (in other words, if a directory named 99 exists but it's not in your list you want to exclude it), you can iterate over the list:

list="10 12 13 14 18 24"; for dir in $list; do cd "$dir"; do_something "foo $dir bar"; done

or an array:

array=(10 12 13 14 18 24); for idx in ${!array[@]}; do cd "${array[idx]}"; do_something "foo ${array[idx]} bar"; done

You can do previous or next array elements like this: ${array[idx-1]} or ${array[idx+1]} if you do appropriate checks to make sure you're not trying to retrieve an element with a negative index (an index beyond the last element will return a null).

or:

array=(10 12 13 14 18 24); for dir in ${array[@]}; do cd "$dir"; do_something "foo $dir bar"; done

which is essentially the same as the list example above.


base=$PWD; for num in *; do cd $base/$num; cp /home/files/*Session${num}.* .; svn add *Session${num}.*; svn commit; done


Time for the find-based solution.

find . -maxdepth 1 -regextype posix-extended -type d -regex '.*/[0-9]{2}$' -exec \
    bash -c 'dir=${1##*/}
    cd $1 
    cp /home/files/*Session{$dir}.* . 
    svn add *Session${dir}.* 
    svn commit'  -- {} \;

EDIT: now more findy than ever.

0

精彩评论

暂无评论...
验证码 换一张
取 消