3

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.

1 Answer 1

6

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:]]'`
Sign up to request clarification or add additional context in comments.

4 Comments

And if you're on an ancient shell that doesn't support that kind of substitution: echo "${file}" | tr -cd '0-9'
Thanks, Yes that's right, let me add that also in answer.
@Jenny_Winters if this answer is exactly what you needed, then please accept it.
I will absolutely do that one the minimum time limit is up! Thanks for your suggestion!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.