Andy
Andy

Reputation: 1092

Get part of filename

I try to get the number of the file num23.txt by using only one bash variable.

User@User-MacBook-Pro:~$ f=num23.txt
User@User-MacBook-Pro:~$ echo $f
num23.txt
User@User-MacBook-Pro:~$ echo ${f%.txt}
num23
User@User-MacBook-Pro:~$ echo ${f/num}
23.txt
User@User-MacBook-Pro:~$ echo ${f/num%.txt}
num23.txt
User@User-MacBook-Pro:~$

I try to use only the % and / operators. How could it change the last command to get as output only 23?

Upvotes: 4

Views: 85

Answers (1)

ROMANIA_engineer
ROMANIA_engineer

Reputation: 56714

Get the number

For your particular example (when you have only one substring having only digits):

echo ${f//[^0-9]/} 

or

echo ${f//[^[:digit:]]/}

Get the string between prefix and suffix

But if you want to specify the suffix and the prefix of that string, you have the following alternative:

echo `basename ${f/num} .txt`

because echo ${f/num%.txt} doesn't work properly and Bash doesn't allow you to run something like this echo ${${f/num}%.txt}.

Upvotes: 3

Related Questions