Fun at work!

Posts tagged ‘Shell Scripting’

Link

Repost: “Shell Scripting: Convert Uppercase to Lowercase”

Repost: “Shell Scripting: Convert Uppercase to Lowercase”

Use the tr command to convert all incoming text / words / variable data from upper to lower case or vise versa (translate all uppercase characters to lowercase). Bash version 4.x+ user can use parameter expansion to modify the case of alphabetic characters in parameter.

Convert all text in a file from UPPER to lowercase

To translate or delete characters use tr command. The basic syntax is:

tr 'set1' 'set2' input

OR

tr 'set1' 'set2' input > output

Type the following command at shell prompt:
$ tr '[:upper:]' '[:lower:]' < input.txt > output.txt
$ cat output.txt

Task: Convert Data Stored in a Shell Variable From UPPER to lowercase:

Type the following command:
$ echo $VAR_NAME | tr '[:upper:]' '[:lower:]'
$ echo $VAR_NAME | tr '[:lower:]' '[:upper:]'

Bash version 4.x+: Uppercase to lowercase or vice versa

The bash version 4.x+ got some interesting new features. Type the following commands to convert $y into uppercase:

 
y="this Is A test"
echo "${y^^}"

Sample outputs:

THIS IS A TEST

Type the following commands to convert $y into lowercase:

 
y="THIS IS a TeSt"
echo "${y,,}"

Sample outputs:

this is a test

Sample Shell Script

#!/bin/bash
# get filename
echo -n "Enter File Name : "
read fileName

# make sure file exits for reading
if [ ! -f $fileName ]; then
  echo "Filename $fileName does not exists."
  exit 1
fi

# convert uppercase to lowercase using tr command
tr '[A-Z]' '[a-z]' < $fileName

# Note Bash version 4 user should use builtins as discussed above
Advertisements

Tag Cloud