Save time and destroy the world with bash

Posted on 27th March, 2011 | Tagged:

Using a bash for loop in the shell is an extremely powerfull way to apply global changes to code, and has proved essential for me when upgrading Symfony2 PRs :) But I always forget the syntax, so I am sharing the wealth.

Search and replace in matching files

for i in `find -name "*ImporterExtension.php"`; do cat $i | sed -e 's/function extend/function extendSiteImport/g' > $i.new; mv $i.new $i; done;

This will find all files names matching "ImporterExtension", pipe the contents to sed which pipes the output to a file called [original filename].new, which is then moved to the original filename, overwriting it. This is necessary I think as if you redirect the output to the same file you are cat'ing it will be blank and your code will disapear ...

"git mv" (rename) all files matching a pattern

for i in `find -type f name "twig.html"`; do git mv $i `echo $i | sed 's/twig.html/html.twig/g'; done; 

Upper case matches and underscore space between 2 words

e.g. <foobar label="Do Something" help="Help me"/> to <foorbar label="DO_SOMETHING" help="Help me"/>

for i in `find ./ -name '*.xml' | egrep "site_config|navigation|global" | grep -v skeleton`; do cat $i | sed -e 's/label="\([^\"]*\)"/label="\U\1"/g' | sed -e 's/label="\([A-Z]*\)[[:blank:]]\([A-Z]*\)[[:blank:]]\([A-Z]*\)"/label="\1_\2_\3"/g' > $i.new; mv $i.new $i; done;

I have to run this at least 2 times to match 2 words and then 3 words, am sure there is a better way..

Comments

Be the first to leave a comment.

Post new comment


type "i hate spam" in UPPER CASE

Tags

10 Latest Items