Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract substring in Bash

Given a filename in the form someletters_12345_moreleters.ext, I want to extract the 5 digits and put them into a variable.

So to emphasize the point, I have a filename with x number of characters then a five digit sequence surrounded by a single underscore on either side then another set of x number of characters. I want to take the 5 digit number and put that into a variable.

I am very interested in the number of different ways that this can be accomplished.

like image 912
Berek Bryan Avatar asked Jan 09 '09 13:01

Berek Bryan


People also ask

How do I cut a string after a specific character in bash?

In Bash (and ksh, zsh, dash, etc.), you can use parameter expansion with % which will remove characters from the end of the string or # which will remove characters from the beginning of the string. If you use a single one of those characters, the smallest matching string will be removed.

How do I print a string in bash?

To print a string in Bash, use echo command. Provide the string as command line argument to echo command.


2 Answers

You can use Parameter Expansion to do this.

If a is constant, the following parameter expansion performs substring extraction:

b=${a:12:5} 

where 12 is the offset (zero-based) and 5 is the length

If the underscores around the digits are the only ones in the input, you can strip off the prefix and suffix (respectively) in two steps:

tmp=${a#*_}   # remove prefix ending in "_" b=${tmp%_*}   # remove suffix starting with "_" 

If there are other underscores, it's probably feasible anyway, albeit more tricky. If anyone knows how to perform both expansions in a single expression, I'd like to know too.

Both solutions presented are pure bash, with no process spawning involved, hence very fast.

like image 128
JB. Avatar answered Sep 20 '22 13:09

JB.


Use cut:

echo 'someletters_12345_moreleters.ext' | cut -d'_' -f 2 

More generic:

INPUT='someletters_12345_moreleters.ext' SUBSTRING=$(echo $INPUT| cut -d'_' -f 2) echo $SUBSTRING 
like image 38
FerranB Avatar answered Sep 20 '22 13:09

FerranB