我在UNIX中编写脚本,我必须检查字符串中的第一个字符是否为“/”,如果是,则为branch。
例如,我有一个字符串:
/some/directory/file
我希望这返回1,并且:
[email protected]:/some/directory/file
返回0。
许多方法可以做到这一点。您可以在双括号中使用通配符:
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
考虑case语句,它与大多数基于sh的shell兼容:
case "$STRING" in
/*)
echo 1
;;
*)
echo 0
;;
esac
$ 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
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?