2015年11月28日 星期六

[Linux 文章收集] Shell Scripting: Convert Uppercase to Lowercase

Source From Here 
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: 
# tr 'set1' 'set2' input
OR
# tr 'set1' 'set2' input > output

Type the following command at shell prompt: 
# cat input.txt
THIS IS For Testing
# tr '[:upper:]' '[:lower:]' < input.txt > output.txt
# cat output.txt
this is for testing

Task: Convert Data Stored in a Shell Variable From UPPER to lowercase: 
Type the following command: 
# export VAR_NAME='This is for Testing'
# echo $VAR_NAME
This is for Testing
# echo $VAR_NAME | tr '[:upper:]' '[:lower:]'
this is for testing
# echo $VAR_NAME | tr '[:lower:]' '[:upper:]'
THIS IS FOR TESTING

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: 
# echo $BASH_VERSION
4.1.2(1)-release
# bash --version
bash --version
GNU bash, version 4.1.2(1)-release (x86_64-redhat-linux-gnu)
...

# echo ${VAR_NAME}
This is for Testing
# echo ${VAR_NAME,,}
this is for testing
# echo ${VAR_NAME^^}
THIS IS FOR TESTING

Sample Shell Script 
- test.sh 
  1. #!/bin/bash  
  2. # get filename  
  3. echo -n "Enter File Name : "  
  4. read fileName  
  5.   
  6. # make sure file exits for reading  
  7. if [ ! -f $fileName ]; then  
  8.     echo "Filename $fileName does not exists."  
  9.     exit 1  
  10. fi  
  11.   
  12. # convert uppercase to lowercase using tr command  
  13. tr '[A-Z]' '[a-z]' < $fileName  
  14.   
  15. # Note Bash version 4 user should use builtins as discussed above  
Test the above script: 
# ./test.sh
Enter File Name : input.txt
this is for testing

Supplement 
[Linux 命令] tr : 更換或變更檔案中的字元

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...