Four curious ways to operate with string in bash or zsh - upper and lower case

Four curious ways to operate with string in bash or zsh - upper and lower case | Janis Janovskis

I have been a great admirer and a fan of Unix (not only Linux) shell terminals ever since I dived into the Linux world more than a decade ago.

In this post, I will be sharing with you a number of curious ways on how to operate with strings within Linux terminals - uppercase and lowercase transformations in particular. 

Let's start with the best terminal program available - works on most terminals:

Option 1 - awk

According to Wikipedia "awk": "AWK is a domain-specific language designed for text processing and typically used as data extraction and reporting tool. Like sed and grep, it is a filter and is a standard feature of most Unix-like operating systems"

 

echo "FOUR CURIOUS WAYS TO OPERATE WITH STRING IN BASH OR ZSH - UPPER AND LOWER CASE" | awk '{print tolower($0)}'

 

As I mentioned - straight forward. Try to change "tolower" to "toupper" and see what it does.

This works on every shell you have the awk program installed

Option 2 - string transformation (works on Linux bash)

Linux bash is perhaps the most powerful scripting engine in the world; to determine if you are within bash shell type:

echo "${SHELL}"

If you're on bash, then, the terminal output should return:

/bin/bash

Let's see how we can code it this time:

y="FOUR CURIOUS WAYS TO OPERATE WITH STRING IN BASH OR ZSH - UPPER AND LOWER CASE"

echo "${y,,}"

If you are curious then change variable "y" to a lower-case string and do this on the terminal:

echo "${y^^}"

Pay attention to the output on the screen

Option 3  - tr command

According to Wikipedia, the "tr" command comes as: "It is an abbreviation of translate or transliterate, indicating its operation of replacing or removing specific characters in its input data set."

Basically, it means - replace one set of specifics with a different kind of specifics 

echo "FOUR CURIOUS WAYS TO OPERATE WITH STRING IN BASH OR ZSH - UPPER AND LOWER CASE" | tr '[:upper:]' '[:lower:]'

Again; not complex and easy to learn and works on both bash and zsh shells (Linux and Mac).

Option 4 - Inherently declaring a variable lowercase or uppercase

Sounds rather complex but in the essence it's simple.

typeset -l name

Just tells the terminal that the preceding variable will be an uppercase string.

name="FOUR CURIOUS WAYS TO OPERATE WITH STRING IN BASH OR ZSH - UPPER AND LOWER CASE"

Sets the value for the variable. Then, we just need to print it on the screen.

echo $name

Easy - isn't it? Happy hacking.

Sources.

I compiled this tutorial on four curious ways to operate with string in bash or zsh - upper and lower case from these sources:

Not because I wanted to nit our earn without giving credit to its creators, because I dreamed on making these things be easier for you to comprehend.