Alex Rivera | Logout

Extract pattern from a string

Asked 2012-07-18T01:21:45.907
17

In bash script, what is the easy way to extract a text pattern from a string?

For example, I want to extract X followed by 2 digits in the end of the string?

Edit
Report

1 Answer

8
$ foo="abcX23"
$ echo "$(echo "$foo" | sed 's/.*\(X[0-9][0-9]\)$/\1/')"
X23

or

if [[ "$foo" =~ X[0-9][0-9]$ ]]; then
  echo "${foo:$((${#foo}-3))}"
fi
answered 2012-07-18T01:28:03.300

Your Answer