Made by Nathan

programming and projects

Search and Replace in Multiple Files on Linux With Bash, Egrep, Sed Function

| Comments

Heres a simple function to add to your shell if you ever want to replace a string in multiple files at once. It ignores everything in .git, otherwise you get ‘bad index file sha1 signature’ errors.

function gsed () {
  if [ -z "$3" ]
    echo "== Usage:    gsed search_string replace_string [path]"
    egrep --exclude-dir=.git -lRZ "$1" $3 | xargs -0 -l sed -i -e "s/$1/$2/g"

Add it to the bottom of ~/.bashrc

So you might want to replace all occurences of ‘badly_named_method’ with ‘awesome_method_name’, recursively for the current directory? You would type:

  gsed "badly_named_ruby_method" "awesome_method_name" .

Note: quotes are optional for single words.