Monday, December 12, 2005

Cygwin Bash script: fully qualified Java class name into clipboard

Purpose. Take a Java class name and output the fully qualified Java name (package + class name).

Input. A valid Java class name. You should be able to do the following search with it: "find . -name ClassName.java".

Output. Fully qualified Java class name, output to the console and to the system clipboard.

Code:

#!/bin/bash

# Get a file name and convert '/' to '.' and place in system clipboard.
if [ $# -ne 1 ]
then
 echo Get a file name and convert '/' to '.' and place in system clipboard.
 echo Usage: $0 fileNameToConvert
 exit 1
fi

extension=
echo "$1" | grep ".java$"

if [ $? -ne 0 ]
then
 extension=".java"
fi

file=`find . -iname "${1}${extension}"`

if [ $? -ne 0 ]
then
 echo Failed to find file: $1
 exit 2
fi

# Replace path separators with package separators.
result=`echo $file | sed 's/\//./g' | sed 's/[.]java//g'`
# Remove leading source directory.
result=`echo $result | sed 's/\.\.src\.//g'`
# Remove leading dots.
result=`echo $result | sed 's/^\.\.//g'`

echo -n $result | putclip
echo $result