Resume

Tuesday, June 2, 2015

How to refactor names without an IDE

At my current client the IDE I'm using doesn't work very well with JavaScript. In fact, it can lock up the whole IDE if you even try certain types of refactoring.

Worse, I am restricted from installing another IDE (thanks, group policies!) However, I do have Cygwin

Here's my little find/replace script that only modifies files where the find :

#!usr/bin/bash
DIR=$1
FIND=$2
REPLACE=$3
GREP_RX="\b$FIND\b"
SED_RX="s/\b$FIND\b/$REPLACE/g"
$(find $DIR -type f -exec grep -q -l -E $GREP_RX {} \; -print0 | xargs -0 sed -b -i $SED_RX)

Explanation

find $dir -type f
Find files in $DIR that are files (no directories)

-exec grep -q -l -E $GREP_RX {} \;
Execute a grep search for each found file and looking for the $FIND string, but only whole matching words. If match not found, exit quietly (-q), otherwise print the file name (-l).

-print 0 | xargs -0 sed -b -i $SEX_RX
Print the matching file names with no newline between them. Pipe this list of files to xargs and invoke sed to do an in-place find/replace, treating each file as a binary file so that line endings are not changed.

P.S., I had to run dos2unix on the script to get it to run in Cygwin.