我一直在学习shell脚本和正则表达式。 我想找到一种从下面的文件名中提取特定部分的方法。
profiles_060315091024_30398-r-00006.avro
我想从文件名中提取数字30398。
由于
答案 0 :(得分:1)
使用awk
:
str='profiles_060315091024_30398-r-00006.avro'
awk -F'[_-]' '{print $3}' <<< "$str"
30398
-F'[_-]'
将自定义字段分隔符设置为_
或-
答案 1 :(得分:0)
仅使用shell。我假设你想要下划线和连字符之间的数字。
正则表达式(特定于bash)
filename=profiles_060315091024_30398-r-00006.avro
if [[ $filename =~ _([0-9]+)- ]]; then num=${BASH_REMATCH[1]}; fi
echo $num
# => 30398
使用参数扩展(任何POSIX shell)
tmp=${filename##*_} # remove from the start up to last underscore
tmp=${tmp%%-*} # remove the first hyphen until end of string
echo $tmp
# => 30398