5

The following line removes the leading text before the variable $PRECEDING

temp2=${content#$PRECEDING}

But now i want the $PRECEDING to be case-insensitive. This works with sed's I flag. But i can't figure out the whole cmd.

tshepang
  • 12,111
  • 21
  • 91
  • 136
jjacobs
  • 57
  • 1
  • 5
  • possible duplicate of [Case Insensitive comparision of strings in Shell script](http://stackoverflow.com/questions/1728683/case-insensitive-comparision-of-strings-in-shell-script) – Riot Aug 25 '15 at 17:46

5 Answers5

9

No need to call out to sed or use shopt. The easiest and quickest way to do this (as long as you have Bash 4):

if [ "${var1,,}" = "${var2,,}" ]; then
  echo "matched"
fi

All you're doing there is converting both strings to lowercase and comparing the results.

Riot
  • 15,723
  • 4
  • 60
  • 67
4

Here's a way to do it with :

temp2=$(sed -e "s/^.*$PRECEDING//I" <<< "$content")

Explanation:

  • ^.*$PRECEDING: ^ means start of string, . means any character, .* means any character zero or more times. So together this means "match any pattern from start of string that is followed by (and including) string stored in $PRECEDING.
  • The I part means case-insensitive, the g part (if you use it) means "match all occurrences" instead of just the 1st.
  • The <<< notation is for herestrings, so you save an echo.
sampson-chen
  • 45,805
  • 12
  • 84
  • 81
  • This deletes only the $PRECEDING variable. with gI it also is case-insensitive!! But how do you also delete the leading text before the $PRECEDING variable? – jjacobs Dec 13 '12 at 16:16
  • @user1898411 see updated answer: (`^.*$PRECEDING` instead of `$PRECEDING`) – sampson-chen Dec 13 '12 at 16:20
1

The only bash way I can think of is to check if there's a match (case-insensitively) and if yes, exclude the appropriate number of characters from the beginning of $content:

content=foo_bar_baz
PRECEDING=FOO
shopt -s nocasematch
[[ $content == ${PRECEDING}* ]] && temp2=${content:${#PRECEDING}}
echo $temp2

Outputs: _bar_baz

glenn jackman
  • 238,783
  • 38
  • 220
  • 352
1

your examples have context-switching techniques. better is (bash v4):

VAR1="HELLoWORLD"
VAR2="hellOwOrld"

if [[ "${VAR1^^}" = "${VAR2^^}" ]]; then
    echo MATCH
fi

link: Converting string from uppercase to lowercase in Bash

Thomas Fritsch
  • 9,639
  • 33
  • 37
  • 49
0

If you don't have Bash 4, I find the easiest way is to first convert your string to lowercase using tr

VAR1=HelloWorld
VAR2=helloworld

VAR1_LOWER=$(echo "$VAR1" | tr '[:upper:]' '[:lower:]')
VAR2_LOWER=$(echo "$VAR2" | tr '[:upper:]' '[:lower:]')

if [ "$VAR1_LOWER" = "$VAR2_LOWER" ]; then
  echo "Match"
else
  echo "Invalid"
fi

This also makes it really easy to assign your output to variables by changing your echo to OUTPUT="Match" & OUTPUT="Invalid"

Daniel Rich
  • 159
  • 2
  • 5