Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch copy and rename multiple files

Tags:

bash

I would like to batch copy and rename all files from a directory, recursively.

I have something like this:

/dir/subdir/file.aa
/dir/subdir/fileb.aa
/dir/filec.aa

and would like all files to be copied as this:

/newdir/1.xx
/newdir/2.xx
/newdir/3.xx
/newdir/4.xx

.. /newdir/nn.xx

How can I do this in bash?

like image 311
Leonardo M. Ramé Avatar asked Aug 09 '11 18:08

Leonardo M. Ramé


2 Answers

find -name "*.aa" | cat -n | while read n f; do
    cp "$f" newdir/"$n".xx
done

will work with (nearly) any valid filename (except if you have newlines in it, which would be allowed as well).

If you are not restricted to the shell, another solution in python could be

#!/usr/bin/env python

if __name__ == '__main__':
    import sys
    import os
    import shutil
    target = sys.argv[1]
    for num, source in enumerate(sys.argv[2:]):
        shutil.move(source, os.path.join(target, "%d.xx" % num))

which then could be called as

<script name> newdir *.aa
like image 200
glglgl Avatar answered Oct 08 '22 13:10

glglgl


Try sth. like this:

num=0
for i in `find -name "*.aa"`; do
    let num=num+1
    cp $i newdir/$lc.xx
done
like image 21
ypnos Avatar answered Oct 08 '22 13:10

ypnos