Refactoring code with find xargs sed

With the script to follow you can do:

# changed lines only 
# only in files .php
# under current dir
# but don't make them (0)
sed_multifile .php find replace 0

# make changes and list nothing (1)
sed_multifile .php find replace 1

# replace in all files
sed_multifile "" find replace 0

The script:

#!/usr/bin/env bash

usage()
{
	echo "Usage: sed_multifile dotext find replace dosubstitute"
}

# argument checking
if [ $# -ne 4 ]
then
	usage
	exit
fi

# decide write or not
if [ $4 -eq 0 ]
then # don't replace
	find . -type f -name "*$1" -print0 | xargs -0 sed -n "s/$2/$3/gp"
else # replace
	find . -type f -name "*$1" -print0 | xargs -0 sed -i "s/$2/$3/g"
fi

Just add it to your bash search path.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s