【发布时间】:2014-07-10 11:52:16
【问题描述】:
我想提取子字符串直到最后一个数字结束。
例如:
在字符串 "abcd123z" 中,我希望输出为 "abcd123"
在字符串 "abcdef123gh01yz" 中,我希望输出为 "abcdef123gh01"
在字符串 "abcd123" 中,我希望输出为 "abcd123"
如何在 unix shell 中做到这一点?
【问题讨论】:
我想提取子字符串直到最后一个数字结束。
例如:
在字符串 "abcd123z" 中,我希望输出为 "abcd123"
在字符串 "abcdef123gh01yz" 中,我希望输出为 "abcdef123gh01"
在字符串 "abcd123" 中,我希望输出为 "abcd123"
如何在 unix shell 中做到这一点?
【问题讨论】:
试试这个 sed 命令,
sed 's/^\(.*[0-9]\).*$/\1/g' file
例子:
$ echo 'abcdef123gh01yz' | sed 's/^\(.*[0-9]\).*$/\1/g'
abcdef123gh01
【讨论】:
您可以在 BASH 正则表达式中执行此操作:
str='abcdef123gh01yz'
[[ "$str" =~ ^(.*[[:digit:]]) ]] && echo "${BASH_REMATCH[1]}"
abcdef123gh01
【讨论】:
BASH,因为OP用BASH标记了这个问题
tmp="${str##*[0-9]}" # cut off all up to last digit, keep intermediate
echo "${str%$tmp}" # remove intermediate from end of string
【讨论】: