zl程序教程

您现在的位置是:首页 >  其他

当前栏目

Bash处理字符串系列函数(一)

2023-04-18 12:35:51 时间

文章目录

修剪字符串的前导和尾随空格

这是sedawkperl和其他工具的替代品。下面的函数通过查找所有前导和尾随空格并将其从字符串的开头和结尾移除来工作。 内置的用来代替临时变量。

示例函数:

trim_string() {
    # Usage: trim_string "   example   string    "
    : "${1#"${1%%[![:space:]]*}"}"
    : "${_%"${_##*[![:space:]]}"}"
    printf '%s
' "$_"
}

示例用法:

$ trim_string "    Hello,  World    "
Hello,  World

$ name="   John Black  "
$ trim_string "$name"
John Black

修剪字符串中的所有空白并截断空格

这是sedawkperl和其他工具的替代品。下面的函数通过滥用分词来创建一个没有前导/尾随空格和截断空格的新字符串。

示例函数:

# shellcheck disable=SC2086,SC2048
trim_all() {
    # Usage: trim_all "   example   string    "
    set -f
    set -- $*
    printf '%s
' "$*"
    set +f
}

示例用法:

$ trim_all "    Hello,    World    "
Hello, World

$ name="   John   Black  is     my    name.    "
$ trim_all "$name"
John Black is my name.

在字符串上使用regex

bash正则表达式匹配的结果可以用于替换大量用例中的sed

警告: 这是为数不多的依赖于平台的bash特性之一。 bash将使用用户系统上安装的任何regex引擎。 如果以兼容性为目标,请坚持使用POSIX正则表达式特性。

警告: 本例仅打印第一个匹配组。当使用多个捕获组时,需要进行一些修改。

示例函数:

regex() {
    # Usage: regex "string" "regex"
    [[ $1 =~ $2 ]] && printf '%s
' "${BASH_REMATCH[1]}"
}

示例用法:

$ # Trim leading white-space.
$ regex '    hello' '^s*(.*)'
hello

$ # Validate a hex color.
$ regex "#FFFFFF" '^(#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3}))$'
#FFFFFF

$ # Validate a hex color (invalid).
$ regex "red" '^(#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3}))$'
# no output (invalid)

脚本中的用法示例:

is_hex_color() {
    if [[ $1 =~ ^(#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3}))$ ]]; then
        printf '%s
' "${BASH_REMATCH[1]}"
    else
        printf '%s
' "error: $1 is an invalid color."
        return 1
    fi
}

read -r color
is_hex_color "$color" || color="#FFFFFF"

# Do stuff.