Never been to CodeSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

iregex (See related posts)

function iregex() {
   declare escaped_str iregexstr lower upper
   escaped_str="$(printf "%q" "${1}")"
   iregexstr=
   lower="$(printf "%s" "${escaped_str}" | /usr/bin/tr '[[:upper:]]' '[[:lower:]]')"
   upper="$(printf "%s" "${escaped_str}" | /usr/bin/tr '[[:lower:]]' '[[:upper:]]')"

   for ((i=0; i < "${#lower}"; i++)); do
      iregexstr="${iregexstr}[${lower:${i}:1}${upper:${i}:1}]"
   done

   printf "%s" "${iregexstr}" | /usr/bin/sed -E -e 's/\[([[:space:]])[[:space:]]\]/\1/g'  -e 's/\[([[:punct:]])[[:punct:]]\]/\1/g'
   return 0
}


iregex 'hello \ | / again!?'
re="$(iregex 'hello \ | / again!?')"


# replace the following string
string='helLo \ | / again!?'

re_str='hello \ | / again!?'
iregex "${re_str}"
regex="$(iregex "${re_str}")"   # always use iregex "${re_str}"
echo "${regex}"

echo "${string}" | sed "s/${regex}/replacement worked/g"   # / not escaped in regex
echo "${string}" | sed "s|${regex}|replacement worked|g"   # always use "s|${re}|replacement|"


# note: printf does not escape / to \/ in function iregex above
#printf "%q\n" "/|\ "
printf "%q\n" '/|\'   


# cf. gnused, http://codesnippets.joyent.com/posts/show/1835
string='helLo \ | / again!?'
echo "${string}" | gnused 's/hello \\ | \/ again!?/replacement worked/ig'
echo "${string}" | gnused 's|hello \\ \| / again!?|replacement worked|ig'


#---------------------------------------------------------


# replace the following string containing a tab character \t
string=$'helLo \ | / \tagain!?'
echo "${string}"
iregex "${string}"


re_str1='hello \ | / '
re_str2=$'\t'
re_str3='again!?'

re1="$(iregex "${re_str1}")"
re2="${re_str2}"
re3="$(iregex "${re_str3}")"

echo "${string}" | sed "s|${re1}${re2}${re3}|replacement worked|g"

echo "${string}" | gnused 's|hello \\ \| / \tagain!?|replacement worked|ig'


#---------------------------------------------------------


TAB=$'\t'

echo $'abc\tdef'
echo $'abc\tdef' | sed $'s/\t//'
echo $'abc\tdef' | sed s/$'\t'//
echo $'abc\tdef' | sed "s/${TAB}//"

echo $'abc\tdef' | sed $'s/\t/TAB/'
echo $'abc\tdef' | sed $'s/\t/TAB/' | sed $'s/TAB/\t/'
echo $'abc\tdef' | sed $'s/\t/TAB/' | sed s/TAB/$'\t'/
echo $'abc\tdef' | sed $'s/\t/TAB/' | sed "s/TAB/${TAB}/"


# gnused

echo $'abc\tdef' | sed 's/\t/TAB/'
echo $'abc\tdef' | gnused 's/\t/TAB/'

echo $'abc\tdef' | gnused $'s/\t/TAB/'
echo $'abc\tdef' | gnused "s/${TAB}/TAB/"


echo $'abc\tdef' | gnused $'s/\t/TAB/' | gnused $'s/TAB/\t/'
echo $'abc\tdef' | gnused $'s/\t/TAB/' | gnused s/TAB/$'\t'/
echo $'abc\tdef' | gnused $'s/\t/TAB/' | gnused "s/TAB/${TAB}/"

echo $'abc\tdef' | gnused 's/\t/TAB/' | gnused 's/TAB/\t/'


You need to create an account or log in to post comments to this site.