2015年10月12日 星期一

[Linux 常見問題] Bash - Using regex match string

Source From Here
Question
As title. How to use regex to compare string in Bash?

How-To
To match regexes you need to use the =~ operator. For example:
- testReg.sh
  1. #!/bin/bash  
  2. IFS='\n' read -a array <<< `find ~/ -type f -name "*.sh"`  
  3.   
  4. for element in ${array[@]}  
  5. do  
  6.     [[ $element =~ test.* ]] && echo "$element (o)" || echo "$element (x)"  
  7. done  
Execution sample:
# ./testReg.sh
/root/test.sh /root/testReg.sh /root/tmp/test/test.sh /root/abc.sh
/root/test.sh (o)
/root/testReg.sh (o)
/root/tmp/test/test.sh (o)
/root/abc.sh (x)
Alternatively, you can use wildcards (instead of regexes) with the == operator:
  1. #!/bin/bash  
  2. IFS='\n' read -a array <<< `find ~/ -type f -name "*.sh"`  
  3.   
  4. for element in ${array[@]}  
  5. do  
  6.     [[ $element == *test* ]] && echo "$element (o)" || echo "$element (x)"  
  7. done  
Execution result:
# ./testReg.sh
/root/test.sh (o)
/root/testReg.sh (o)
/root/tmp/test/test.sh (o)
/root/abc.sh (x)


沒有留言:

張貼留言

[ FP with Java ] Ch3 - Making Java more functional - Part1

Preface This chapter covers *  Making standard control structures functional *  Abstracting control structures *  Abstracting iter...