4

I can remove a pattern in a bash variable using ${variable##pattern} (leading) or ${variable%%pattern} (trailing).

But I can't find a bash-only way to keep the pattern and throw the rest.

I know there are solutions using sed, awk, or grep, but I want to know if there is a reasonably efficient bash-only solution that I am overlooking?

0
7
${var%"${var##pattern}"}
${var#"${var%%pattern}"}

Example:

$ k='ab*10cd20ef*'
$ echo "${k%"${k##*[0-9]}"}"
ab*10cd20
$ echo "${k#"${k%%[0-9]*}"}"
10cd20ef*

Note the quotes are important to prevent the shell from interpreting the expansions as a pattern. Try echo "${k#${k%%[0-9]*}}" to see it outputs an incorrect result.

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.