In bash, given a path such as:
mypath='my/path/to/version/5e/is/7/here'
I would like to extract the first part that contains a number. For the example I would want to extract: 5e
Is there a better way than looping over the parts using while and checking each part for a number?
while IFS=/ read part
do
if [[ $part =~ *[0-9]* ]]; then
echo "$part"
fi
done <<< "$mypath"
If we want any element of the path, it is best to use something that can break up a string into fields, such as awk, cut , python, or perl. However, bash can also do the job with parameter substitution,using pattern replacement and throwing everything into an array.
We can extract from the Nth until the Mth character from the input string using the cut command: cut -c N-M. As we’ve discussed in an earlier section, our requirement is to take the substring from index 4 through index 8. Here, when we talk about the index, it’s in Bash’s context, which means it’s a 0-based index.
You can of course also use Bash variables instead of a file name or pipe data into the cut command: Show activity on this post. You could do it directly in your read command, using the IFS variable e.g.
You can of course also use Bash variables instead of a file name or pipe data into the cut command: Show activity on this post. You could do it directly in your read command, using the IFS variable e.g. Show activity on this post. Show activity on this post.
Using Bash's regex:
[[ "$mypath" =~ [^/]*[0-9]+[^/]* ]] && echo "${BASH_REMATCH[0]}"
5e
Method using 'grep -o'.
echo $mypath | grep -o -E '\b[^/]*[0-9][^/]*\b' | head -1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With