1

I have discovered how to get my string in bash as lower case:

> multi_case='MULTIcaseSTRING'
> echo ${multi_case,,}
multicasestring

...and how to get the last two letters of the string:

> echo ${multi_case:(-2)}
NG

... but I don't know how to combine them.

How do I get the last two letters in lowercase? If it helps, I know that the string will always be two to five chars long.

Ideally, I'm looking for a fairly short one-liner.

meshy
  • 8,470
  • 9
  • 51
  • 73
  • 1
    Unfortunately I don't think you can nest these expansions, so you might be better off defining a function if you find yourself doing these two things together often. – Tom Fenech Sep 07 '15 at 16:25
  • 1
    I have bash 3.2.25 and `echo ${multi_case,,}` throws "Bad Substitution" – Alvaro Flaño Larrondo Sep 07 '15 at 16:26
  • This question has already an answer [here][1] and you may find other info [here][2] [1]: http://stackoverflow.com/questions/2264428/converting-string-to-lower-case-in-bash-shell-scripting [2]: http://askubuntu.com/questions/383352/command-to-convert-an-upper-case-string-to-lower-case – Vargan Sep 07 '15 at 16:29
  • 2
    @AlvaroFlañoLarrondo The `,,` and `^^` (uppercase) operators were added in `bash` 4. – chepner Sep 07 '15 at 18:00

2 Answers2

2

You can "abuse" a for loop for it (in case you are sure that the variable does not contain any wildcards or whitespace):

for i in ${multi_case,,}; do echo ${i:(-2)}; done

But in practice, I'd go for a temporary variable:

TMP=${multi_case,,}; echo ${TMP:(-2)}
mihi
  • 6,507
  • 1
  • 38
  • 48
1

Not pure bash but you can use tr to get this done in single line:

multi_case='MULTIcaseSTRING'
tr '[[:upper:]]' '[[:lower:]]' <<< "${multi_case:(-2)}"
ng
anubhava
  • 761,203
  • 64
  • 569
  • 643