程式扎記: [Linux 常見問題] Bash - String contains in Bash

標籤

2016年8月21日 星期日

[Linux 常見問題] Bash - String contains in Bash

Source From Here 
Question 
Using Bash, I have a string = "My string". How can I test if it contains another string? For example: 
  1. if [ $string ?? 'foo' ]; then  
  2.   echo "It's there!"  
  3. fi  
Where ?? is my unknown operator. Do I use echo and grep

How-To 
You can use Marcus's answer (* wildcards) outside a case statement, too, if you use double brackets: 
- test.sh 
  1. #!/bin/sh  
  2. string="My long string"  
  3.   
  4. function contain()  
  5. {  
  6.     echo -e "\t[Info] Check '$1' contains '$2'?"  
  7.     if [[ $1 == *"$2"* ]]; then  
  8.         echo "Hit!"  
  9.     else  
  10.         echo "Miss!"  
  11.     fi  
  12. }  
  13.   
  14. contain "$string" "My long"  
  15. contain "$string" "Missing string"  
Execution result: 
# ./test.sh
[Info] Check 'My long string' contains 'My long'?
Hit!
[Info] Check 'My long string' contains 'Missing string'?
Miss!

Note that spaces in the needle string need to be placed between double quotes, and the * wildcards should be outside the double quotes.

沒有留言:

張貼留言

網誌存檔