Tuesday 18 January 2011

Copying and renaming files in Linux / UNIX

I had a problem of multiple locations containing the same file names, but wanting to copy all those files into the one directory to back them up. The file structure looked something like this:

./somewhere/install1/conf/webserver1.conf
./somewhere/install1/conf/webserver2.conf
./somewhere/install1/conf/webserver3.conf
./somewhere/install1/conf/webserver4.conf
./somewhere/install2/conf/webserver1.conf
./somewhere/install2/conf/webserver2.conf
./somewhere/install2/conf/webserver3.conf
./somewhere/install2/conf/webserver4.conf

If I was to copy the files over into the same location, some of the files would overwrite files which had a similar name. So, with the following line, I manipulated the target filename to retain the original location of the file:

$ for i in $(find . -name webserver*.conf | grep -v backup | grep -v Trace | grep -v LocalConfig); do cp $i /tmp/mylocation/$(echo $i|sed 's/\//_/g'|sed 's/^\._//g'); done

The final result is:

/tmp/mylocation/somewhere_install1_conf_webserver1.conf
/tmp/mylocation/somewhere_install1_conf_webserver2.conf
/tmp/mylocation/somewhere_install1_conf_webserver3.conf
/tmp/mylocation/somewhere_install1_conf_webserver4.conf
/tmp/mylocation/somewhere_install2_conf_webserver1.conf
/tmp/mylocation/somewhere_install2_conf_webserver2.conf
/tmp/mylocation/somewhere_install2_conf_webserver3.conf
/tmp/mylocation/somewhere_install2_conf_webserver4.conf

While this could have been made into a script, I have not done it in a full script. Therefore it is not apart of the shell scripting tutorial series I was writing for Kitty Kat.

I have also noticed that a few people are reading this, and making suggestions to me via email. Please feel free to share your comments on this and all the articles on this blog, by using the comments link at the bottom of every blog posting.

No comments:

Post a Comment