string KSH 检查字符串是否以子字符串开头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4080388/
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:52:41  来源:igfitidea点击:

KSH check if string starts with substring

shellstringksh

提问by z4y4ts

I need to check if the variable has value of string which starts with specified substring.

我需要检查变量是否具有以指定子字符串开头的字符串值。

In Python it would be something like this:

在 Python 中,它会是这样的:

foo = 'abcdef'
if foo.startswith('abc'):
    print 'Success'

What is the most explicit way to check in Ksh whether strig $foostarts with substring bar?

在 Ksh 中检查 srig 是否$foo以 substring 开头的最明确的方法是什么bar

回答by Aaron Digulla

It's very simple but looks a bit odd:

这很简单,但看起来有点奇怪:

if [[ "$foo" == abc* ]]; then ...

One would assume that ksh would expand the pattern with the files in the current directory but instead, it does pattern matching. You need the [[, though. Single [won't work. The quotes are not strictly necessary if there are no blanks in foo.

人们会假设 ksh 将使用当前目录中的文件扩展模式,但相反,它进行模式匹配。但是,您需要[[。单身[不行。如果foo.

回答by glenn Hymanman

Also:

还:

foo='abcdef'
pattern='abc*'

case "$foo" in
    $pattern) echo startswith ;;
    *) echo otherwise ;;
esac

回答by Paused until further notice.

You can also do regex matching:

您还可以进行正则表达式匹配:

if [[ $foo =~ ^abc ]]

For more complex patterns, I recommend using a variable instead of putting the pattern directly in the test:

对于更复杂的模式,我建议使用变量而不是将模式直接放在测试中:

bar='^begin (abc|def|ghi)[^ ]* end$'
if [[ $foo =~ $bar ]]