Open In App

Shell Script to Convert a File Content to Lower Case or Upper Case

Here we are going to see how to convert a file to lower case or upper case as specified by the user. We are going to write a  POSIX  compatible shell script which is going to give us the desired output after input of files such as sample.txt, a text file with a combination of lowercase, uppercase, digits and special character

Example:



File Content

this is lowercase

THIS IS UPPERCASE

$P3C14L C#4R4CT3R$

1234567890

OUTPUT

Uppercase

THIS IS LOWERCASE

THIS IS UPPERCASE

$P3C14L C#4R4CT3R$

1234567890

Lowercase

this is lowercase

this is uppercase

$p3c14l c#4r4ct3r$

1234567890

Approach:

Shell Script 

#!/bin/sh
# shebang to specify that this is an shell script

# Function to get File
getFile(){
    # Reading txtFileName to convert it's content
    echo -n "Enter File Name:"
    read txtFileName
    # Checking if file exist
    if [ ! -f $txtFileName ]; then
        echo "File Name $txtFileName does not exists."
        exit 1
    fi
}

clear
  echo "1. Uppercase to Lowercase "
  echo "2. Lowercase to Uppercase"
  echo "3. Exit"
  echo -n "Enter your Choice(1-3):"
  read Ch

  case "$Ch" in
    1) 
      # Function Call to get File 
      getFile    
      # Converting to lower case if user choose 1     
      echo "Converting Upper-case to Lower-Case "
      tr '[A-Z]' '[a-z]' <$txtFileName
    ;;

    2)
      # Function Call to get File 
      getFile
      # Converting to upper case if user cho0se 2
      echo "Converting Lower-Case to Upper-Case "
      tr '[a-z]' '[A-Z]' <$txtFileName
    ;;
    

    *) # exiting for all other cases
        echo "Exiting..."
        exit
    ;;
  esac

Output:

Sample text file and making our script executable

Showcasing content of sample text file with cat command and modifying our script by making it executable with chmod command.



Conversion Input and Output

Converting file content from uppercase to lowercase

Converting file content from lowercase to uppercase

Running on non-existing files

In the Case File does not exist

Article Tags :