Extract substring in Bash
bash, shell, string, substring
Solution
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
Problem
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.
Related problems
- Why does /bin/sh behave differently to /bin/bash even if one points to the other?
- Bash regex =~ operator
- I just assigned a variable, but echo $variable shows something else
- Are double square brackets [[ ]] preferable over single square brackets [ ] in Bash?
- When to wrap quotes around a shell variable?
- What is the purpose of "&&" in a shell command?
- What linux shell command returns a part of a string?