程式扎記: [Linux 常見問題] Bash - Using regex match string

標籤

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)


沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!