Skip to content


Search and Replace in Bash script

Had a colleague ask me how to do in-line regular expression matching for a Bash shell script. Since Bash v3 only offers a regex matching check and not the full s/foo/bar/ syntax, I offered to look into other alternatives.

My natural instinct was to look for a Perl cmdline regex parser, which works great if you're manipulating a file and not shell variables.

In the end, since he only needed a simple search and replace, and not an actual regular express, this suffices:

#!/bin/bash
VAR1="foobar"
VAR2=`echo $VAR1 | awk -v srch="foo" -v repl="bar" \
   '{ sub(srch,repl,$0); print $0 }'`
echo $VAR1
echo $VAR2

Posted in devops, howto.

Tagged with .


3 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

  1. lowlevelmanager.com/ says

    your awk could be replaced with perl -p:
      VAR2= ` echo $VAR1 | perl -pe 's/foo/bar/g' `
    I prefer the readability of $( ) over “ for shell escaping.  (Plus, I use back-tick as my screen key,  as you know)
      VAR2=$( echo $VAR1 | perl -pe 's/foo/bar/g' )
    Or hey, you could be using zsh for the shell script:
      #!/usr/bin/zwsh

      VAR1="FOO"

      VAR2=${VAR1:s/FOO/BAR}
      echo "1:$VAR1, 2:$VAR2"


    –andrew
    ps. Thanks for making me look up the zsh syntax for this particular  "parameter expansion"

  2. lowlevelmanager.com/ says

    your awk could be replaced with perl -p:
      VAR2= ` echo $VAR1 | perl -pe 's/foo/bar/g' `

    I prefer the readability of $( ) over “ for shell escaping.  (Plus, use back-tick as my screen key,  as you know)
      VAR2=$( echo $VAR1 | perl -pe 's/foo/bar/g' )
     
    Or hey, you could be using zsh for the shell script:
      #!/usr/bin/zsh
      VAR1="FOO"
      VAR2=${VAR1:s/FOO/BAR}
      echo "1:$VAR1, 2:$VAR2"

    –andrew
    ps. Thanks for making me look up the zsh syntax for this particular  "parameter expansion"

Continuing the Discussion

  1. Search and Replace in Bash script – iandouglas.com | Linux Blog linked to this post on August 16, 2011

    [...] is the original post: Search and Replace in Bash script – iandouglas.com This entry was posted in Uncategorized and tagged alternatives, colleague-ask, [...]

You must be logged in to post a comment.


Get Adobe Flash player