开发者

Extract numbers from filename

In BASH I thought to use sed, but can't figure how to extract pattern instead usual replace.

For example:

FILENAME = 'blah_blah_#######_blah.ext'

number of ciphers (in above开发者_C百科 example written with "#" substitute) could be either 7 or 10

I want to extract only the number


If all you need is to remove anything but digits, you could use

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

to get all digits grouped per filename (123test456.ext will become 123456), or

ls | egrep -o [0-9]+

for all groups of numbers (123test456.ext will turn up 123 and 456)


You can use this simple code:

filename=zc_adsf_qwer132467_xcvasdfrqw
echo ${filename//[^0-9]/}   # ==> 132467


Just bash:

shopt -s extglob
filename=zc_adsf_qwer132467_xcvasdfrqw
tmp=${filename##+([^0-9])}
nums=${tmp%%+([^0-9])}
echo $nums   # ==> 132467

or, with bash 4

[[ "$filename" =~ [0-9]+ ]] && nums=${BASH_REMATCH[0]}


Is there any number anywhere else in the file name? If not:

 ls | sed 's/[^0-9][^0-9]*\([0-9][0-9]*\).*/\1/g'

Should work.

A Perl one liner might work a bit better because Perl simply has a more advanced regular expression parsing and will give you the ability to specify the range of digits must be between 7 and 10:

ls | perl -ne 's/.*\D+(\d{7,10}).*/$1/;print if /^\d+$/;'


$ ls -1
blah_blah_123_blah.ext
blah_blah_234_blah.ext
blah_blah_456_blah.ext

Having such files in a directory you run:

$ ls -1 | sed 's/blah_blah_//' | sed 's/_blah.ext//'
123
234
456

or with a single sed run:

$ ls -1 | sed 's/^blah_blah_\([0-9]*\)_blah.ext$/\1/'


This will work for you -

echo $FILENAME | sed -e 's/[^(0-9|)]//g' | sed -e 's/|/,/g'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜