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:
- Ask User Choice if they want to convert from Uppercase to Lowercase or vice-versa
- Read the choice
- Get into the Switch case depending on the choice. while exiting if the choice is none of the above-mentioned.
- Asking user for the filename
- Checking if file exists, if not then exit with error code 1, otherwise continue
- Translating the file content as per the previous selected user choice and printing the output by the use of tr command.
- End of Script
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:
Showcasing content of sample text file with cat command and modifying our script by making it executable with chmod command.
Conversion Input and Output
Running on non-existing files
Article Tags :