Sunday, 29 December 2019

Useful script for moving files

Periodically I get a large number of files arrive from various servers that have a similar naming convention. I need to manage these files quickly to push them into various folders. Here is an example of the naming convention:

ServerXX.FileZZZZ.bak

So there are two elements to these files - the server ID (XX) and the number of the file - from 0000 to 9999. I want to search for files from Server01 and copy all of them to a directory. How do I do this quickly? With the magic of bash command line scripting!

So here is what the single line script looks like:

for i in `find . -name Server01.File*.bak` ; do cp $i /path/to/storage/Server01/ ; done

To break this down a bit:

for i in `find . -name Server01.File*.bak` assigns all files that match the name Server01.File*.bak to the variable i.

The * serves as a wildcard, so it matches all the files from 0000 to 9999.

The next bit:

do cp $i /path/to/storage/Server01/ copies all the files that are assigned to the $i variable to the location I want them to go.

And the ; done finishes the script. Neat huh? The "name" bit could be anything.

Enjoy!

No comments:

Post a comment