Reputation: 2386
i'd like to return only the digits from a string variable in bash shell. For example, for:
#!/bin/sh
file="./file_02.txt"
file_num_tag=?????????????????
echo $file_num_tag
...i'd like to return
>>> 02
I know this is super trivial, but I'm confusing myself searching around for answers and I'd like to know the best way to do it.
Upvotes: 3
Views: 60
Reputation: 784938
You can use this BASH string replacement:
file="./file_02.txt"
echo "${file//[^[:digit:]]}"
02
[^[:digit:]]
will match and remove all non-digits from your string file
.
Or using tr
(if not using BASH):
num=`echo "$file" | tr -cd '[[:digit:]]'`
Upvotes: 6