Comment vérifier si une chaîne contient un sous-chaîne dans Bash

Mots clés : stringbashshellsubstringstring

meilleur 5 Réponses Comment vérifier si une chaîne contient un sous-chaîne dans Bash

vote vote

97

string='My long string' if [[ $string == *"My long"* ]]; then   echo "It's there!" fi 
vote vote

84

string='My string';  if [[ $string =~ "My" ]]; then    echo "It's there!" fi 
vote vote

77

case "$string" in    *foo*)     # Do stuff     ;; esac 
vote vote

64

[ -z "${string##*$reqsubstr*}" ] 
string='echo "My string"' for reqsubstr in 'o "M' 'alt' 'str';do   if [ -z "${string##*$reqsubstr*}" ] ;then       echo "String '$string' contain substring: '$reqsubstr'."     else       echo "String '$string' don't contain substring: '$reqsubstr'."     fi   done 
String 'echo "My string"' contain substring: 'o "M'. String 'echo "My string"' don't contain substring: 'alt'. String 'echo "My string"' contain substring: 'str'. 
myfunc() {     reqsubstr="$1"     shift     string="$@"     if [ -z "${string##*$reqsubstr*}" ] ;then         echo "String '$string' contain substring: '$reqsubstr'.";       else         echo "String '$string' don't contain substring: '$reqsubstr'."     fi } 
$ myfunc 'o "M' 'echo "My String"' String 'echo "My String"' contain substring 'o "M'.  $ myfunc 'alt' 'echo "My String"' String 'echo "My String"' don't contain substring 'alt'. 
$ myfunc 'o "M' echo "My String" String 'echo My String' don't contain substring: 'o "M'.  $ myfunc 'o "M' echo \"My String\" String 'echo "My String"' contain substring: 'o "M'. 
stringContain() { [ -z "${2##*$1*}" ]; } 
$ if stringContain 'o "M3' 'echo "My String"';then echo yes;else echo no;fi no $ if stringContain 'o "M' 'echo "My String"';then echo yes;else echo no;fi yes 
stringContain() { [ -z "${2##*$1*}" ] && [ -z "$1" -o -n "$2" ]; } 
stringContain() { [ -z "${2##*$1*}" ] && { [ -z "$1" ] || [ -n "$2" ];};} 
stringContain() { [ -z "$1" ] || { [ -z "${2##*$1*}" ] && [ -n "$2" ];};} 
$ if stringContain '' ''; then echo yes; else echo no; fi yes $ if stringContain 'o "M' ''; then echo yes; else echo no; fi no 
stringContain() {     local _lc=${2,,}     [ -z "$1" ] || { [ -z "${_lc##*${1,,}*}" ] && [ -n "$2" ] ;} ;} 
stringContain 'o "M3' 'echo "my string"' && echo yes || echo no no stringContain 'o "My' 'echo "my string"' && echo yes || echo no yes if stringContain '' ''; then echo yes; else echo no; fi yes if stringContain 'o "M' ''; then echo yes; else echo no; fi no 
vote vote

58

if grep -q foo <<<"$string"; then     echo "It's there" fi 
## Instead of this filetype="$(file -b "$1")" if grep -q "tar archive" <<<"$filetype"; then #...  ## Simply do this if file -b "$1" | grep -q "tar archive"; then #... 

Questions similaires