Question
I've a small shell script and I would like to convert all incoming user input to lowercase using a shell script. How do I convert uppercase words or strings to a lowercase or vise versa on Unix-like / Linux bash shell?
How-To
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:
Type the following command at shell prompt:
Task: Convert Data Stored in a Shell Variable From UPPER to lowercase:
Type the following command:
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:
Sample Shell Script
- test.sh
- #!/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
Supplement
* [Linux 命令] tr : 更換或變更檔案中的字元
沒有留言:
張貼留言