在bash中获取文件名的数字部分

时间:2016-07-01 20:58:03

标签: bash

我的文件名就像

AAA_BBB_CCC_6-28_04-12-33PM/fetch_352.txt
AAA_BBB_CCC_6-28_04-12-33PM/fetch_351.txt
AAA_BBB_CCC_6-28_04-12-33PM/fetch_2.txt

如何在bash中从中获取数值3523512

我试过

ls | sed -e s/[^0-9]//g

但它给了我类似628041233352

的东西

2 个答案:

答案 0 :(得分:1)

awk救援!

$ awk -F'[_.]' '{print $(NF-1)}' <<< "AAA_BBB_CCC_6-28_04-12-33PM/fetch_352.txt
> AAA_BBB_CCC_6-28_04-12-33PM/fetch_351.txt                                                                           
> AAA_BBB_CCC_6-28_04-12-33PM/fetch_2.txt"   

352
351
2

使用分隔符_.并打印倒数第二个字段。

答案 1 :(得分:0)

使用shell parameter expansion运算符。

filename=AAA_BBB_CCC_6-28_04-12-33PM/fetch_352.txt
num=${filename##*_} # remove everything through the last _
num=${num%.txt} # remove .txt suffix
echo $num # should print 352
相关问题