Sunday, April 4, 2010

Advanced find/replace commands in Linux

Working on a recent SOA/AIA project, I had to write numerous recursive find/replace commands to update hostnames, ports, values, etc.

Below are some random examples with a brief explanation.

Example 1 - Recursively find a string

Recursively search through all files in $ORACLE_HOME/bpel/domains/default/tmp and list out the filenames that have the hostname string "dev78.net" in them.

find $ORACLE_HOME/bpel/domains/default/tmp -type f | xargs grep "dev78.net"
Example 2 - Recursively replace a string

Recursively search from the current directory, and replace all references of "orabpel" with "orabpel2" in all files.

find . -type f -exec sed -i "s%orabpel%orabpel2%" {} \;
Example 3 - Recursively replace a string in a specific location within the line

In the command below, everything between the first % and the second % represents the original search string. Everything between the second % and the third % is the new string to be replaced.

find . -type f -exec sed -i "s%\(<soapEndpointURI>\)\(.*\)?wsdl\(.*\)%\1\2\.wsdl\?wsdl\3%" {} \;
The original search string consists of 4 parts:
(1) <soapEndpointURI>
(2) *
(the string "?wsdl" in between 2 and 3)
(3) *
The new string search string keeps parts 1, 2, and 3 intact, but replaces the text in between with ".wsdl?wsdl".

So if the original string looked like this:


<soapEndpointURI>http://thisisahmed/hello?wsdl</soapEndpointURI>
It would now look like this:
<soapEndpointURI>http://thisisahmed/hello.wsdl?wsdl</soapEndpointURI>
Example 4 - Exclude files
Same as Example 3, but will not search/replace inside of .class, .jar, or .zip files.
find . -type f \( -iname "*.class" ! -iname "*.jar" ! -iname "*.zip" \) -exec sed -i "s%\(\)\(.*\)?wsdl\(.*\)%\1\2\.wsdl\?wsdl\3%" {} \;
Example 5 - Recursively replace the hostname in URLs
For every string that takes the form "http://*:7777" (the * is just a wildcard, but can be any value), replace it with "http://${HOSTNAME}:7777" where ${HOSTNAME} is an environment variable.
find -type f -exec sed -i "s%\(ocation=\"http://\)\(.*\):7777\(.*\)%\1${HOSTNAME}:7777\3%" {} \;

No comments: