如何在Bash或UNIX shell中检查字符串中的第一个字符?

问题描述 投票:57回答:4

我在UNIX中编写脚本,我必须检查字符串中的第一个字符是否为“/”,如果是,则为branch。

例如,我有一个字符串:

/some/directory/file

我希望这返回1,并且:

[email protected]:/some/directory/file

返回0。

string bash unix character exitstatus
4个回答
99
投票

许多方法可以做到这一点。您可以在双括号中使用通配符:

str="/some/directory/file"
if [[ $str == /* ]]; then echo 1; else echo 0; fi

您可以使用子字符串扩展:

if [[ ${str:0:1} == "/" ]] ; then echo 1; else echo 0; fi

或正则表达式:

if [[ $str =~ ^/ ]]; then echo 1; else echo 0; fi

14
投票

考虑case语句,它与大多数基于sh的shell兼容:

case "$STRING" in
/*)
    echo 1
    ;;
*)
    echo 0
    ;;
esac

9
投票
$ foo="/some/directory/file"
$ [ ${foo:0:1} == "/" ] && echo 1 || echo 0
1
$ foo="[email protected]:/some/directory/file"
$ [ ${foo:0:1} == "/" ] && echo 1 || echo 0
0

1
投票

cut -c1

这是POSIX,与case不同,如果你以后需要它,它实际上会提取第一个字符:

myvar=abc
first_char="$(printf '%s' "$myvar" | cut -c1)"
if [ "$first_char" = a ]; then
  echo 'starts with a'
else
  echo 'does not start with a'
fi

awk substr是另一个POSIX但效率较低的替代品:

printf '%s' "$myvar" | awk '{print substr ($0, 0, 1)}'

printf '%s'是为了避免逃脱字符的问题:https://stackoverflow.com/a/40423558/895245例如:

myvar='\n'
printf '%s' "$myvar" | cut -c1

按预期输出\

${::}似乎不是POSIX。

另见:How to extract the first two characters of a string in shell scripting?

© www.soinside.com 2019 - 2024. All rights reserved.