Extract numbers from file name

In BASH, I thought of using sed , but I can't figure out how to extract the template instead of the usual replacement.

For instance:

FILENAME = 'blah_blah _ ####### _ blah.ext'

the number of ciphers (in the above example, written with the replacement "#"), can be 7 or 10

I want to extract only the number

+4
source share
6 answers

If you only need to delete the numbers, you can use

 ls | sed -es/[^0-9]//g 

to get all the numbers grouped by file name (123test456.ext will become 123456), or

 ls | egrep -o [0-9]+ 

for all groups of numbers (123test456.ext appears 123 and 456)

+4
source

You can use this simple code:

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

Just bash:

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

or, bash 4

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

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

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

Must work.

One Perl liner might work a little better, because Perl just has a more advanced regex analysis and will give you the ability to specify a range of numbers in the range of 7 to 10:

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

The presence of such files in the directory that you run:

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

or with one sed run:

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

This will work for you -

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

All Articles