Gabriel Saul
Gabriel Saul

Reputation: 83

Extract pattern from a string in a bash script

Somewhat new to bash.

I've experimented with parameter expansions, grep, sed and echo to solve this problem, but cannot quite work it out.

I'm trying to extract a certain pattern from $PWD in a bash script.

Let's say there could be a variety of full paths:

/home/files/tmp8
/home/tmp28/essential
/home/tmp2/essential/log
/home/files/tmp10/executables
/tmp8/files/whatever/etc

In every instance, I want to extract any string that contains "tmp" followed by 1 or more integers.

So, in each instance in which $PWD is processed, it will return "tmp8", "tmp28", "tmp2" etc.

Explanations for how the functions/operators work in regards to solving this issue would also be greatly appreciated.

Upvotes: 4

Views: 6721

Answers (2)

lojoe
lojoe

Reputation: 521

You can use regular expressions in bash to extract a pattern from any path string. See the following example:

if [[ "$PWD" =~ ^.*(tmp[0-9]+).*$ ]]
then
    printf "match: ${BASH_REMATCH[1]}\n"
else
    printf "no match: $PWD\n"
fi

The regular expression defines a group in the round parenthesis. If the expression matches the matching group (tmp with at least one digit following) it will be stored by Bash in the array BASH_REMATCH.

Upvotes: 6

anubhava
anubhava

Reputation: 785196

Use grep -o to show only matched text using regex tmp[0-9]* i.e. literal text tmp followed by 0 or more digits:

grep -o 'tmp[0-9]*' file
tmp8
tmp28
tmp2
tmp10
tmp8

Upvotes: 1

Related Questions