Get part of the file name

I am trying to get the file number num23.txtusing 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 operators %and /. How could he change the last command to get only output 23?

+4
source share
1 answer

Get a number

In your specific example (when you have only one substring having only numbers):

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

or

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

Get string between prefix and suffix

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

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

because it echo ${f/num%.txt}doesn’t work correctly, and Bash does not allow you to run something like echo ${${f/num}%.txt}.

+3

Source: https://habr.com/ru/post/1621865/


All Articles