Skip to content

Instantly share code, notes, and snippets.

@micahjon
Last active May 2, 2016 15:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save micahjon/2af6e3525304312f34d7 to your computer and use it in GitHub Desktop.
Save micahjon/2af6e3525304312f34d7 to your computer and use it in GitHub Desktop.
Bash Snippets
### Find & Replace
## basic examples
# replaces "urchin" with "analytics" in all files in current directory and backs up originals as .bak files
find . -type f -exec sed -i.bak "s/urchin.js/analytics.js/g" {} \;
# reverses the prior command, restoring all the original (now .bak) files
find . -name "*.bak" -exec sh -c 'mv -f $0 ${0%.bak}' {} \;
# replace Windows linebreaks (\r\n that unix renders as ^M) with typical unix \n linebreaks in all html files (no backup)
find . -name "*.html" -type f -exec sed -i "s/\r/\n/g" {} \;
# for multi-line (and generally more complex) regex replacements, use "perl -i.bak -p00 -e" instead of "sed -i.bak"
# for instance, this replaces consecutive Google Analytics urchin.js script tags:
# <script .. urchin.js ...></script>\n<script... urchinTracker ...</script> tags
# with Google Tag Manager code (abbreviated as GTM --- remember to escape any / and ! in this second string)
find . -name "*.html" -type f -exec perl -i -p00 -e "s/<script [^>]*urchin\.js[^>]*>.*?<\/script>\n<script[^<]+urchinTracker[^<]+<\/script>/GTM/s" {} \;
## most reliable syntax
# find wrapper around command (represented as ......)
find -name "*.htm" -type f -exec .......... {} \;
## command: perl string replacement
# string 1 can be a perl regex. string 2 needs to have / and ! escaped
perl -i -p -e "s/string1/string2/"
# adding in multiline capacity (00 after p, and /s at end allows .* to match across lines)
perl -i -p00 -e "s/string1/string2/s"
# and of course, if you need a backup, -i.bck does the trick.
# replacing <? with <?php in php files (but not replacing <?=)
find . -name "*.php" -type f -exec perl -i -p00 -e "s/<\?\n/<?php\n/s" {} \;
find . -name "*.php" -type f -exec perl -i -p00 -e "s/<\?\s/<?php /s" {} \;
# for capturing groups escape $, e.g. \$1 for first group. for "$" string, double escape, e.g. \\$
# replacing <?php$test with <?php $test to fix a faulty prior regex due to capture groups not working
find . -name "*.php" -type f -exec perl -i -p -e "s/<\?php(\S)/<?php \$1/" {} \;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment