I need to compare two strings and ignoring the case of the contents. IF [ $first != $second ]. Anything I can add to this command so that the comparison ignores the case.
Asked
Active
Viewed 1.9k times
1 Answers
25
In bash, you can perform case conversions easily e.g. if var="vAlUe" then
$ echo "${var^^}"
VALUE
while
$ echo "${var,,}"
value
You can use this to make you comparison case-insensitive by converting both arguments to the same case, i.e.
if [ "${first,,}" == "${second,,}" ]; then
echo "equal"
fi
or
if [ "${first^^}" == "${second^^}" ]; then
echo "equal"
fi
Another approach is to use the bash nocasematch option (thanks @Tshilidzi_Mudau), although this appears to work only with the [[ ... ]] extended test operator:
$ first=abc; second=ABC
$ (shopt -s nocasematch; if [[ "$first" == "$second" ]]; then echo "Match"; else echo "No match"; fi)
Match
but
$ (shopt -s nocasematch; if [ "$first" == "$second" ]; then echo "Match"; else echo "No match"; fi)
No match
~$
steeldriver
- 131,985
- 21
- 239
- 326
-
Unfortunately, this does not recognize letters with diacritical marks: `é` is not converted into `É` (or vice versa). – G-Man Says 'Reinstate Monica' Dec 10 '15 at 00:27
-
Is your locale define for the correct (with diacritics) letters, @G-Man? (http://askubuntu.com/questions/17001/how-to-set-locale) – boardrider Dec 10 '15 at 10:22
-
@boardrider: Well, (a) my default locale is en_US.UTF-8, (b) I'm not willing to make non-volatile configuration changes (even if reversible) or install software on my machine just to test this, and (c) I'm doing this on Cygwin, which might not be 100% representative of Unix. But (1) even in the en_US.UTF-8 locale, I can do `var="àÉîö"` and `echo "$var"`, and it correctly regurgitates the characters that I gave it, and (2) I started a new shell with `LANG=fr_FR.UTF-8 bash`, and "${var^^}" and "${var,,}" still just give me `àÉîö`. … (Cont’d) – G-Man Says 'Reinstate Monica' Dec 10 '15 at 21:32
-
(Cont’d) … And I believe that I have effectively set bash’s locale, because (a) when I type `type foo`, it says `bash: type: foo : non trouvé`, and (b) `env | grep LC_` and `set | grep LC_` give no output. Can you suggest anything else to try? – G-Man Says 'Reinstate Monica' Dec 10 '15 at 21:33
-
http://unix.stackexchange.com/questions/84942/how-to-convert-utf-8-txt-files-to-all-uppercase-in-bash might be helpful. – boardrider Dec 11 '15 at 16:02
-
@G-ManSays'ReinstateMonica': The locale *fr_FR.UTF-8* must exist. Otherwise, it may fall back to *C* this creates the behavior you describe. – Dec 18 '20 at 13:14