Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
String 如何在Bash中检查字符串是否包含子字符串_String_Bash_Shell_Substring_Sh - Fatal编程技术网

String 如何在Bash中检查字符串是否包含子字符串

String 如何在Bash中检查字符串是否包含子字符串,string,bash,shell,substring,sh,String,Bash,Shell,Substring,Sh,我在Bash中有一个字符串: string=“我的字符串” 如何测试它是否包含另一个字符串 if[$string???'foo'];然后 回声:“它在那儿!” fi 其中?是我的未知操作员。我是否使用echo和grep if echo“$string”| grep'foo';然后 回声:“它在那儿!” fi 这看起来有点笨拙。我不确定是否使用if语句,但您可以使用case语句获得类似的效果: case "$string" in *foo*) # Do stuff ;;

我在Bash中有一个字符串:

string=“我的字符串”
如何测试它是否包含另一个字符串

if[$string???'foo'];然后
回声:“它在那儿!”
fi
其中
是我的未知操作员。我是否使用
echo
grep

if echo“$string”| grep'foo';然后
回声:“它在那儿!”
fi

这看起来有点笨拙。

我不确定是否使用if语句,但您可以使用case语句获得类似的效果:

case "$string" in 
  *foo*)
    # Do stuff
    ;;
esac
如果使用双括号,也可以在case语句外使用:

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

请注意,指针字符串中的空格需要放在双引号之间,
*
通配符应该在外部。还请注意,使用了一个简单的比较运算符(即
==
),而不是正则表达式运算符
=~

,接受的答案是最好的,但由于有多种方法可以实现,这里有另一种解决方案:

if [ "$string" != "${string/foo/}" ]; then
    echo "It's there!"
fi

${var/search/replace}
$var
,如果找到了
search
的第一个实例,则将其替换为
replace
(未更改
$var
)。如果您尝试不使用任何内容替换
foo
,并且字符串已更改,则显然找到了
foo

如果您更喜欢正则表达式方法:

string='My string';

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

您应该记住,shell脚本不是一种语言,而是一组命令。你本能地认为,这种“语言”要求你遵循
if
[
[[
。这两种命令都只是返回退出状态以指示成功或失败的命令(就像其他所有命令一样)。因此,我会使用
grep
,而不是
[
命令

只要做:


如果grep-q foo
grep-q
用于此目的

使用awk时也一样:

string="unix-bash 2389"
character="@"
printf '%s' "$string" | awk -vc="$character" '{ if (gsub(c, "")) { print "Found" } else { print "Not Found" } }'
输出:

找不到

输出:

发现

原始来源:

这个怎么样:

text="   <tag>bmnmn</tag>  "
if [[ "$text" =~ "<tag>" ]]; then
   echo "matched"
else
   echo "not matched"
fi
text=“bmnmn”
如果[[“$text”=~”];则
回声“匹配”
其他的
回声“不匹配”
fi
试试oobash

它是Bash4的一个OO风格的字符串库。它支持德语umlauts。它是用Bash编写的

许多功能可用:
-base64Decode
-base64Encode
-capitalize
-center
-charAt
-concat
-contains
-count
-endsWith
-equals
-equalsIgnoreCase
-hashCode>-,
-indexOf
-isAlnum
-isAlpha
-isAscii
-isDigit
-isEmpty
-ishdigit
-isSpace
-isPrintable
-isupper-ishipper
-ishipper
-ishipper
>-匹配
-replaceAll
-replaceFirst
-startsWith
-substring
-swapCase
-toString
-toupercase
-trim
,以及
-zfill

请看以下示例:

[Desktop]$String一个testXccc
[桌面]$a.x
真的
[桌面]$a.XtX
假的
.

一个是:

[ $(expr $mystring : ".*${search}.*") -ne 0 ] && echo 'yes' ||  echo 'no'

我发现经常需要这个功能,所以我在我的
.bashrc
中使用了一个自制的shell函数,这样我就可以根据需要频繁地重用它,并使用一个易于记住的名称:

function stringinstring()
{
    case "$2" in
       *"$1"*)
          return 0
       ;;
    esac
    return 1
}
要测试
$string1
(比如说abc)是否包含在
$string2
(比如说123abcABC)中,我只需要运行
stringinstring“$string1”“$string2”
,并检查返回值

stringinstring "$str1" "$str2"  &&  echo YES  ||  echo NO
这也适用于:

if printf -- '%s' "$haystack" | egrep -q -- "$needle"
then
  printf "Found needle in haystack"
fi
阴性试验为:

if ! printf -- '%s' "$haystack" | egrep -q -- "$needle"
then
  echo "Did not find needle in haystack"
fi
我认为这种风格更经典一点——不太依赖于bashshell的特性

--
参数是纯POSIX偏执狂,用于防止输入字符串与选项类似,例如
--abc
-a

注意:在紧密循环中,此代码将比使用内部Bash shell功能慢得多,因为将创建一个(或两个)单独的进程并通过管道连接。

是唯一捕获空格和破折号字符的代码:

# For null cmd arguments checking   
to_check=' -t'
space_n_dash_chars=' -'
[[ $to_check == *"$space_n_dash_chars"* ]] && echo found
# contains(string, substring)
#
# Returns 0 if the specified string contains the specified substring,
# otherwise returns 1.
contains() {
    string="$1"
    substring="$2"

    if echo "$string" | $(type -p ggrep grep | head -1) -F -- "$substring" >/dev/null; then
        return 0    # $substring is in $string
    else
        return 1    # $substring is not in $string
    fi
}

contains "abcd" "e" || echo "abcd does not contain e"
contains "abcd" "ab" && echo "abcd contains ab"
contains "abcd" "bc" && echo "abcd contains bc"
contains "abcd" "cd" && echo "abcd contains cd"
contains "abcd" "abcd" && echo "abcd contains abcd"
contains "" "" && echo "empty string contains empty string"
contains "a" "" && echo "a contains empty string"
contains "" "a" || echo "empty string does not contain a"
contains "abcd efgh" "cd ef" && echo "abcd efgh contains cd ef"
contains "abcd efgh" " " && echo "abcd efgh contains a space"

contains "abcd [efg] hij" "[efg]" && echo "abcd [efg] hij contains [efg]"
contains "abcd [efg] hij" "[effg]" || echo "abcd [efg] hij does not contain [effg]"

contains "abcd *efg* hij" "*efg*" && echo "abcd *efg* hij contains *efg*"
contains "abcd *efg* hij" "d *efg* h" && echo "abcd *efg* hij contains d *efg* h"
contains "abcd *efg* hij" "*effg*" || echo "abcd *efg* hij does not contain *effg*"
stringContain
变体(兼容或独立于大小写) 正如这些堆栈溢出的答案主要讲述的那样,我在这篇文章的最底部发布了一个与大小写无关的Bash函数

不管怎样,这是我的

兼容答案 由于使用Bash特定功能已经有很多答案,因此有一种方法可以在功能较差的shell下工作,如:

实际上,这可以提供:

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
这是在Bash、(
ksh
)和(BusyBox)下测试的,结果总是:

String'echo“My String”包含子字符串:“o”M“。
字符串“echo”My String“不包含子字符串:“alt”。
字符串“echo”My String包含子字符串:“str”。
合并为一个函数 正如@EeroAaltonen所问,这里是同一个演示的一个版本,在相同的外壳下测试:

myfunc(){
reqsubstr=“$1”
转移
string=“$@”
如果[-z“${string##*$reqsubstr*}”];则
回显“字符串'$String'包含子字符串:'$reqsubstr'。”;
其他的
echo“字符串'$String'不包含子字符串:'$reqsubstr'。”
fi
}
然后:

$myfunc'o“M”回显“我的字符串”'
字符串“echo”My String“包含子字符串“o”M”。
$myfunc'alt''回显“我的字符串”'
字符串“echo”My String“不包含子字符串“alt”。
注意:您必须转义或双引号和/或双引号:

$myfunc'o'M'回显“我的字符串”
字符串“echo My String”不包含子字符串:“o“M”。
$myfunc'o'M'echo\'My String\'
字符串“echo“My String”包含子字符串:“o”M
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
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
/usr/bin/time bash -c 'a=two;b=onetwothree; x=100000; while [ $x -gt 0 ]; do TEST ; x=$(($x-1)); done'
[[ $b =~ $a ]]           2.92 user 0.06 system 0:02.99 elapsed 99% CPU

[ "${b/$a//}" = "$b" ]   3.16 user 0.07 system 0:03.25 elapsed 99% CPU

[[ $b == *$a* ]]         1.85 user 0.04 system 0:01.90 elapsed 99% CPU

case $b in *$a):;;esac   1.80 user 0.02 system 0:01.83 elapsed 99% CPU

doContain $a $b          4.27 user 0.11 system 0:04.41 elapsed 99%CPU
echo $b|grep -q $a       12.68 user 30.86 system 3:42.40 elapsed 19% CPU !ouch!
if echo "abcdefg" | grep -q "bcdef"; then
    echo "String contains is true."
else
    echo "String contains is not true."
fi
[[ $string == *foo* ]] && echo "It's there" || echo "Couldn't find"
substr="foo"
nonsub="$(echo "$string" | sed "s/$substr//")"
hassub=0 ; [ "$string" != "$nonsub" ] && hassub=1
string='My long string'
exactSearch='long'

if grep -E -q "\b${exactSearch}\b" <<<${string} >/dev/null 2>&1
  then
    echo "It's there"
  fi
# .bash_profile
# Get the aliases and functions
if [ -f ~/.bashrc ]; then
    . ~/.bashrc
fi

U=~/.local.bin:~/bin

if ! echo "$PATH" | grep -q "home"; then
    export PATH=$PATH:${U}
fi
function str_instr {
   # Return position of ```str``` within ```string```.
   # >>> str_instr "str" "string"
   # str: String to search for.
   # string: String to search.
   typeset str string x
   # Behavior here is not the same in bash vs ksh unless we escape special characters.
   str="$(str_escape_special_characters "${1}")"
   string="${2}"
   x="${string%%$str*}"
   if [[ "${x}" != "${string}" ]]; then
      echo "${#x} + 1" | bc -l
   else
      echo 0
   fi
}

function test_str_instr {
   str_instr "(" "'foo@host (dev,web)'" | assert_eq 11
   str_instr ")" "'foo@host (dev,web)'" | assert_eq 19
   str_instr "[" "'foo@host [dev,web]'" | assert_eq 11
   str_instr "]" "'foo@host [dev,web]'" | assert_eq 19
   str_instr "a" "abc" | assert_eq 1
   str_instr "z" "abc" | assert_eq 0
   str_instr "Eggs" "Green Eggs And Ham" | assert_eq 7
   str_instr "a" "" | assert_eq 0
   str_instr "" "" | assert_eq 0
   str_instr " " "Green Eggs" | assert_eq 6
   str_instr " " " Green "  | assert_eq 1
}
    if [[ "${str,,}" == *"yes"* ]] ;then
    if [[ "$(echo "$str" | tr '[:upper:]' '[:lower:]')" == *"yes"* ]] ;then
     if [[ "${str}" == *"yes"* ]] ;then
     if [[ "${str}" =~ "yes" ]] ;then
     if [[ "${str}" == "yes" ]] ;then
     if [[ "${str,,}" == "yes" ]] ;then
     if [ "$a" = "$b" ] ;then
     if echo "$a" | egrep -iq "\.(mp[3-4]|txt|css|jpg|png)" ; then
# contains(string, substring)
#
# Returns 0 if the specified string contains the specified substring,
# otherwise returns 1.
contains() {
    string="$1"
    substring="$2"

    if echo "$string" | $(type -p ggrep grep | head -1) -F -- "$substring" >/dev/null; then
        return 0    # $substring is in $string
    else
        return 1    # $substring is not in $string
    fi
}

contains "abcd" "e" || echo "abcd does not contain e"
contains "abcd" "ab" && echo "abcd contains ab"
contains "abcd" "bc" && echo "abcd contains bc"
contains "abcd" "cd" && echo "abcd contains cd"
contains "abcd" "abcd" && echo "abcd contains abcd"
contains "" "" && echo "empty string contains empty string"
contains "a" "" && echo "a contains empty string"
contains "" "a" || echo "empty string does not contain a"
contains "abcd efgh" "cd ef" && echo "abcd efgh contains cd ef"
contains "abcd efgh" " " && echo "abcd efgh contains a space"

contains "abcd [efg] hij" "[efg]" && echo "abcd [efg] hij contains [efg]"
contains "abcd [efg] hij" "[effg]" || echo "abcd [efg] hij does not contain [effg]"

contains "abcd *efg* hij" "*efg*" && echo "abcd *efg* hij contains *efg*"
contains "abcd *efg* hij" "d *efg* h" && echo "abcd *efg* hij contains d *efg* h"
contains "abcd *efg* hij" "*effg*" || echo "abcd *efg* hij does not contain *effg*"
[ ${_string_##*$_substring_*} ] || echo Substring found!
[ "${_string_##*$_substring_*}" ] || echo 'Substring found!'
[ -z "${_string_##*$_substring_*}" ] && echo 'Substring found!'
[ -n "${_string_##*$_substring_*}" ] || echo 'Substring found!'
[ "${_string_##$_substring_}" != "$_string_" ] && echo 'Substring found!'
[ "${_string_##$_substring_}" = "$_string_" ] || echo 'Substring found!'
msg="message"

function check {
    echo $msg | egrep [abc] 1> /dev/null

    if [ $? -ne 1 ];
    then 
        echo "found" 
    else 
        echo "not found" 
    fi
}

check
#!/bin/bash

needle="a_needle"
haystack="a_needle another_needle a_third_needle"
if [[ $haystack == *"$needle"* ]]; then
    echo "needle found"
else
    echo "needle NOT found"
fi