LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Compare string (capitol letters) abc to ABC (https://www.linuxquestions.org/questions/linux-newbie-8/compare-string-capitol-letters-abc-to-abc-755926/)

Willy Fog 09-17-2009 10:00 AM

Compare string (capitol letters) abc to ABC
 
I want compare two strings

if [ "$string1" == "$string2" ] ...

It works. But I want to compare without distinction between "abc" and "ABC". I mean...

¿abc = ABC? YEs!!!!
¿aBc = ABC? Yes !!!!.

How can i change a expresión to capitol letters.

:-)

David the H. 09-17-2009 10:44 AM

If you're using bash v.4, it's easy. It has some new parameter substitution rules for case conversion.
Code:

$ string1="FoObAr"

$ echo ${string1,,}    #echo as lowercase
foobar

$ echo ${string1^^}    #echo as uppercase
FOOBAR

The "declare" command in bash4 also has options for forcing a variable to always be upper or lower case.

Code:

$ declare -u string1="FoObAr"
$ echo $string1
FOOBAR

$ declare -l string1="FoObAr"
$ echo $string1
foobar

For previous versions of bash, or other shells, you can always use tr or a similar tool to convert the strings to one case before checking.
Code:

string1="$(echo $string1 | tr [a-z][A-Z])"    # converts string to uppercase

or

string1="$(echo $string1 | tr [A-Z] [a-z])"    # converts string to lowercase

If you're using non-ascii characters, make sure your tr command is set to handle them.
And of course, if you want to keep the original strings intact, then create two new variables and test them instead.

le37 09-17-2009 10:52 AM

To change a string to uppercase (or lowercase) you can use translate (abbreviated as tr). For example:

echo 'linux' | tr "a-z" "A-Z"

will give the output:

LINUX

so tr "variable" "range 1" "range 2" takes everything it finds in variable from range 1 and translates it to its partner in range 2. I haven't used it in the context your describing before but it should work ok.

Hope this helps,

Luke.

catkin 09-17-2009 11:21 AM

Quote:

Originally Posted by le37 (Post 3687138)
To change a string to uppercase (or lowercase) you can use translate (abbreviated as tr). For example:

echo 'linux' | tr "a-z" "A-Z"

Under some locale settings A-Z can give unexpected results. See "We use the fancy range notation, because tr can behave very strangely when using the A-Z range on some locales" on Greg's WIKI Bash FAQ. Safer to set the locale to C or use POSIX ranges
Code:

echo 'linux' | LC_ALL=C tr 'A-Z' 'a-z'
echo 'linux' | tr '[:upper:]' '[:lower:]'


le37 09-17-2009 11:36 AM

Interesting stuff. Thanks :-)

Luke.


All times are GMT -5. The time now is 07:17 PM.