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.

沒有留言:

張貼留言

[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...