Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting part of path containing a number in bash

Tags:

regex

bash

awk

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"
like image 373
Michael Frey Avatar asked Sep 17 '20 12:09

Michael Frey


People also ask

How do I break up a string into fields in Bash?

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.

How do I get nth to MTH in Bash?

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.

How can I use Bash variables instead of file names?

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.

How do I show activity in a bash file?

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.


Video Answer


2 Answers

Using Bash's regex:

[[ "$mypath" =~ [^/]*[0-9]+[^/]* ]] && echo "${BASH_REMATCH[0]}" 
5e
like image 63
James Brown Avatar answered Oct 20 '22 08:10

James Brown


Method using 'grep -o'.

echo $mypath | grep -o -E '\b[^/]*[0-9][^/]*\b' | head -1
like image 3
etsuhisa Avatar answered Oct 20 '22 08:10

etsuhisa