Replace file name suffix using Groovy scripting

Simple high-level filename utility in Groovy using AntBuilder. Contrasts with one-line shell script examples.

This could be written in one line in most scripting languages, including Groovy too. Gets messy and unreadable in my opinion. Plus, its rather complex. For example, I tried this using PowerShell, just to see whats involved, but it didn’t work:

dir c:temp*.THM | foreach {move-item -destination "c:temp"
 -path c:temp$_ $_.Name.replace(".THM",".JPG")}

Sure, I could figure it out or search the web for solution. The way to really do it is just using ‘dir, SED, then xargs, perhaps. And, would be the ideal solution. On Windows, cygwin would supply all the tools.

I think the script below is at a “higher level” and so, maintainable.

/**
 * File: ReplaceSuffix.groovy
 * Replace filename suffixes.
 * Scenario, digital camera creates file.MPG but also file.THM.
 * THM files are JPG, so having the JPG extension is desired.
 * Sample command shell run in Win7 on Sony camera output files.
 * groovy srcReplaceSuffix c:temp THM JPG
 *
 * Code below is sample only and is on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * ========================================================================
 */

if(args.length < 3){
 println("ERROR! requires <path> <extension> <new_extension>")
 return
}

new AntBuilder().
        move( todir:"${args[0]}", 
		  includeemptydirs:"false"){			
			fileset(dir:"${args[0]}"){}
			regexpmapper(
				casesensitive:"false",
				from:"^(.*).${args[1]}$$",
				to:"1.${args[2]}"
            ){}
}
// end file ReplaceSuffix.groovy

In Ant’s XML syntax this would look something like the following, plus there would be many other complications:

<?xml version="1.0" encoding="UTF-8"?>
<project name="ReplaceSuffix" default="run" basedir=".">
  <!-- set global properties for this build -->
  <target name="init">
    <!-- Create the time stamp -->
    <tstamp/>
    <!-- Create the build directory structure used by compile -->
    <mkdir dir="build"/>
  </target>

  <target name="run" depends="init">  
	  <copy todir="build" includeemptydirs="false">
	    <fileset dir="/temp">
	      <exclude name="**/*.bak"/>
	    </fileset>
	    <regexpmapper casesensitive="false" from="^(.*).THM$$" to="1.JPG"/>
	  </copy>  
  </target>
</project>

Links

Leave a Reply

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