如何将一个字符串拆分为两个字符串?

如何将一个字符串拆分为两个字符串?

我已经知道如何放入h4 h7 h8 h9 h7以空格作为分隔符的数组中,但之后我尝试将h与数字分开以将数字相互比较。

我怎样才能在 bash 脚本中拆分它们?

答案1

#!/bin/bash

arr=( h4 h7 h8 h9 h7 )

for thing in "${arr[@]}"; do
    num=${thing#?}
    printf 'The number in "%s" is %d\n' "$thing" "$num"
done

变量扩展从 中${variable#pattern}删除匹配的最短前缀字符串。该模式匹配单个字符。pattern$variable?

输出将是

The number in "h4" is 4
The number in "h7" is 7
The number in "h8" is 8
The number in "h9" is 9
The number in "h7" is 7

或者,要忽略删除非数字前缀,无论它有多长,请使用sed,

#!/bin/bash

arr=( hello4 happy7 hobbit8 hulk9 hr-department7 )

for thing in "${arr[@]}"; do
    num=$( printf '%s\n' "$thing" | sed 's/^[^[:digit:]]*//' )
    printf 'The number in "%s" is %d\n' "$thing" "$num"
done

或者,使用末尾数字的正则表达式匹配,

#!/bin/bash

arr=( hello4 happy7 hobbit8 hulk9 hr-department7 )

for thing in "${arr[@]}"; do
    if [[ "$thing" =~ ([[:digit:]]+)$ ]]; then
        printf 'The number in "%s" is %d\n' "$thing" "${BASH_REMATCH[1]}"
    fi
done

相关内容