Quick Tip: Quickly Rename a Group of Files with BASH

While configuring Nagios checks for my Asterisk box I stumbled upon something interesting I hadn’t noticed before, PBX in a Flash is based on a 32-bit version of CentOS 6. This was a problem as both my Nagios and Puppet infrastructures are designed to monitor and manage 64-bit machines. A simple if/else statement was all that was required to expand my NRPE Puppet manifest to address both 32 and 64-bit architectures, but the Nagios check files themselves proved more of a challenge.

I use Mcollective with the NRPE plug-in to run an arbitrary check across a set of machines when the need arises and have split my checks into individual <check_name>.cfg files as a result. I then use Puppet to publish those files as resources to my managed nodes. This approach worked wonderfully while I was managing a single architecture, but trying to re-use a check file written for a 64-bit machine against a 32-bit architecture simply wouldn’t work. The simplest thing was to rename the existing check files, alter the plugin path within the new file, and publish the new files to my Asterisk box as additional file resources, but I didn’t want to rename hundreds of check files by hand. Enter a BASH one-liner that uses the for loop we discussed in an earlier post and quickly renames any number of files.

[bash]for file in check_*; do newfilename=$(echo $file | sed s/.cfg/i386.cfg/g); cp $file $newfilename; done[/bash]

The example above builds a list of files in the current directory that begin with check_, creates a variable to hold the new file name, copies the old file to the new filename, and exits the loop. If you have any questions please don’t hesitate to post them in the comments.


Leave a Reply

Your email address will not be published. Required fields are marked *