Search code examples
regexbashvariablesdigits

Extract digits from bash variable


I have this code:

for a in `ls *w.txt`; do perl getSequenceNs.pl $a /home/prenos/medicago/${a:0:1}.NOLE.fas >sequences/${a}_sequence.txt; done

It has been working quite well unless I recognized, that ${a:0:1} extracts first digit from $a and unfortunately there are sometimes two.

So, my variable $a contains:

dsomeletters <-one digit and letters, for example 1.NOLE.fas

ddsomeletters <-two digits and letters, for example 12.NOLE.fas

How can I extract only digits? How should I modify my code (what should I use use instead of ${a:0:1})?


Solution

  • ${a//[^0-9]*} 
    

    should do what you want. That is actually a bashism, so you might prefer the more portable:

    ${a%%[^0-9]*}