如何檢查插入的引數 $1 是否是大寫的 3 個字符的字串?例如ABG。另一個例子:GTD
謝謝
uj5u.com熱心網友回復:
使用 bash-only 正則運算式語法:
#!/usr/bin/env bash
if [[ $1 =~ ^[[:upper:]]{3}$ ]]; then
echo "The first argument is three upper-case characters"
else
echo "The first argument is _not_ three upper-case characters
fi
...或者,為了與所有 POSIX shell 兼容,可以使用以下case陳述句:
#!/bin/sh
case $1 in
[[:upper:]][[:upper:]][[:upper:]])
echo "The first argument is three upper-case characters";;
*)
echo "The first argument is _not_ three upper-case characters";;
esac
uj5u.com熱心網友回復:
我會用:
LC_ALL=C
[[ "$1" == [A-Z][A-Z][A-Z] ]] || exit 1
或者
LC_ALL=C
if [[ "$1" != [A-Z][A-Z][A-Z] ]]; then
echo "$1: invalid input" >&2
exit 1
fi
根據 Charles 的評論,A-Z是一個字符范圍,它不等同于所有語言環境中的“所有大寫拉丁字母”,因此我們可以使用LC_ALL=C.
如果您不想設定[[:upper:]],[A-Z]則可以使用代替LC_ALL=C。
或者,有shopt -s globasciiranges, 但它僅適用于 bash 4.3 或更高版本(并且在 5.0 和更高版本中默認設定)。
另請注意,在字串比較中使用 glob 模式是特定于 bash 的,在sh.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/363386.html
標籤:猛击
