string 如何在 Bash 中比较字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2237080/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 00:39:09  来源:igfitidea点击:

How to compare strings in Bash

stringbash

提问by Erik Sapir

How do I compare a variable to a string (and do something if they match)?

如何将变量与字符串进行比较(并在匹配时执行某些操作)?

回答by John Feminella

Using variables in if statements

在 if 语句中使用变量

if [ "$x" = "valid" ]; then
  echo "x has the value 'valid'"
fi

If you want to do something when they don't match, replace =with !=. You can read more about string operationsand arithmetic operationsin their respective documentation.

如果您想在它们不匹配时执行某些操作,请将其替换=!=。您可以在各自的文档中阅读有关字符串运算算术运算的更多信息。

Why do we use quotes around $x?

为什么我们在周围使用引号$x

You want the quotes around $x, because if it is empty, your Bash script encounters a syntax error as seen below:

您需要 周围的引号$x,因为如果它为空,您的 Bash 脚本会遇到如下所示的语法错误:

if [ = "valid" ]; then


Non-standard use of ==operator

==运营商的不规范使用

Note that Bash allows ==to be used for equality with [, but this is not standard.

请注意,Bash 允许==用于与 相等[,但这不是标准的

Use either the first case wherein the quotes around $xare optional:

使用第一种情况,其中周围的引号$x是可选的:

if [[ "$x" == "valid" ]]; then

or use the second case:

或使用第二种情况:

if [ "$x" = "valid" ]; then

回答by Marko

Or, if you don't need else clause:

或者,如果您不需要 else 子句:

[ "$x" == "valid" ] && echo "x has the value 'valid'"

回答by Guru

a="abc"
b="def"

# Equality Comparison
if [ "$a" == "$b" ]; then
    echo "Strings match"
else
    echo "Strings don't match"
fi

# Lexicographic (greater than, less than) comparison.
if [ "$a" \< "$b" ]; then
    echo "$a is lexicographically smaller then $b"
elif [ "$a" \> "$b" ]; then
    echo "$b is lexicographically smaller than $a"
else
    echo "Strings are equal"
fi

Notes:

笔记:

  1. Spaces between ifand [and ]are important
  2. >and <are redirection operators so escape it with \>and \<respectively for strings.
  1. if[和之间的空格]很重要
  2. >and<是重定向操作符,所以用\>\<分别为字符串转义它。

回答by Jeffrey L. Roberts

To compare strings with wildcards use

使用通配符比较字符串

if [[ "$stringA" == *$stringB* ]]; then
  # Do something here
else
  # Do Something here
fi

回答by Volker Siegel

I have to disagree one of the comments in one point:

我不得不在一点上不同意其中一项评论:

[ "$x" == "valid" ] && echo "valid" || echo "invalid"

No, that is not a crazy oneliner

不,那不是疯狂的单线

It's just it looks like one to, hmm, the uninitiated...

它只是看起来像一个,嗯,外行......

It uses common patterns as a language, in a way;

在某种程度上,它使用通用模式作为一种语言;

And after you learned the language.

在你学会了语言之后。

Actually, it's nice to read

其实读起来很舒服

It is a simple logical expression, with one special part: lazy evaluation of the logic operators.

它是一个简单的逻辑表达式,有一个特殊的部分:逻辑运算符的惰性求值。

[ "$x" == "valid" ] && echo "valid" || echo "invalid"

Each part is a logical expression; the first may be true or false, the other two are always true.

每个部分都是一个逻辑表达式;第一个可能是真的或假的,其他两个总是真的。

(
[ "$x" == "valid" ] 
&&
echo "valid"
)
||
echo "invalid"

Now, when it is evaluated, the first is checked. If it is false, than the second operand of the logic and&&after it is not relevant. The first is not true, so it can not be the first and the second be true, anyway.
Now, in this case is the the first side of the logic or||false, but it could be true if the other side - the third part - is true.

现在,当它被评估时,第一个被检查。如果为假,则与逻辑的第二个操作数及其&&之后的操作数无关。第一个不是真的,所以无论如何它不可能是第一个,第二个是真的。
现在,在这种情况下,是逻辑的第一面 ||假,但如果另一面(第三部分)为真,则它可能为真。

So the third part will be evaluated - mainly writing the message as a side effect. (It has the result 0for true, which we do not use here)

因此将评估第三部分 - 主要是将消息作为副作用编写。(它的结果0为 true,我们在这里不使用)

The other cases are similar, but simpler - and - I promise! are - can be - easy to read!
(I don't have one, but I think being a UNIX veteran with grey beard helps a lot with this.)

其他情况类似,但更简单 - 而且 - 我保证!是 - 可以 - 易于阅读!
(我没有,但我认为作为一名留着灰胡子的 UNIX 老手对此有很大帮助。)

回答by ghostdog74

you can also use use case/esac

你也可以使用用例/esac

case "$string" in
 "$pattern" ) echo "found";;
esac

回答by Harshil

The following script reads from a file named "testonthis" line by line and then compares each line with a simple string, a string with special characters and a regular expression. If it doesn't match, then the script will print the line, otherwise not.

以下脚本逐行读取名为“testonthis”的文件,然后将每一行与一个简单字符串、一个包含特殊字符的字符串和一个正则表达式进行比较。如果不匹配,则脚本将打印该行,否则不打印。

Space in Bash is so much important. So the following will work:

Bash 中的空间非常重要。所以以下将起作用:

[ "$LINE" != "table_name" ] 

But the following won't:

但以下不会:

["$LINE" != "table_name"] 

So please use as is:

所以请按原样使用:

cat testonthis | while read LINE
do
if [ "$LINE" != "table_name" ] && [ "$LINE" != "--------------------------------" ] && [[ "$LINE" =~ [^[:space:]] ]] && [[ "$LINE" != SQL* ]]; then
echo $LINE
fi
done

回答by steviethecat

I would probably use regexp matches if the input has only a few valid entries. E.g. only the "start" and "stop" are valid actions.

如果输入只有几个有效条目,我可能会使用正则表达式匹配。例如,只有“开始”和“停止”是有效的动作。

if [[ "${ACTION,,}" =~ ^(start|stop)$ ]]; then
  echo "valid action"
fi

Note that I lowercase the variable $ACTIONby using the double comma's. Also note that this won't work on too aged bash versions out there.

请注意,我$ACTION使用双逗号将变量小写。另请注意,这不适用于过时的 bash 版本。

回答by Mike Q

Bash 4+ examples. Note: not using quotes will cause issues when words contain spaces, etc. Always quote in Bash, IMO.

Bash 4+ 示例。注意:当单词包含空格等时,不使用引号会导致问题。在 IMO 中始终引用 Bash。

Here are some examples in Bash 4+:

以下是 Bash 4+ 中的一些示例:

Example 1, check for 'yes' in string (case insensitive):

示例 1,检查字符串中的 'yes'(不区分大小写):

    if [[ "${str,,}" == *"yes"* ]] ;then

Example 2, check for 'yes' in string (case insensitive):

示例 2,检查字符串中的 'yes'(不区分大小写):

    if [[ "$(echo "$str" | tr '[:upper:]' '[:lower:]')" == *"yes"* ]] ;then

Example 3, check for 'yes' in string (case sensitive):

示例 3,检查字符串中的 'yes'(区分大小写):

     if [[ "${str}" == *"yes"* ]] ;then

Example 4, check for 'yes' in string (case sensitive):

示例 4,检查字符串中的 'yes'(区分大小写):

     if [[ "${str}" =~ "yes" ]] ;then

Example 5, exact match (case sensitive):

示例 5,完全匹配(区分大小写):

     if [[ "${str}" == "yes" ]] ;then

Example 6, exact match (case insensitive):

示例 6,完全匹配(不区分大小写):

     if [[ "${str,,}" == "yes" ]] ;then

Example 7, exact match:

例7,完全匹配:

     if [ "$a" = "$b" ] ;then

Enjoy.

享受。

回答by shades3002

I did it in this way that is compatible with Bash and Dash(sh):

我是这样做的,与 Bash 和Dash(sh)兼容:

testOutput="my test"
pattern="my"

case $testOutput in (*"$pattern"*)
    echo "if there is a match"
    exit 1
    ;;
(*)
   ! echo there is no coincidence!
;;esac