4

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.

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

6 Comments

Yes sure you can do str=$(grep -o 'tmp[0-9]*' <<< "$PWD") to assign extracted pattern to a variable str
grep -o 'tmp[0-9]*' <<< "$PWD" only returns matched string i.e. tmp<integer> not the full input.
The regex 'tmp[0-9]*' is not correct. That one also matches 'tmp' without a following digit. The star means any cardinality including zero.
Of course I know that. If OP always wants 1 or more digits after tmp then OP can use; grep -Eo 'tmp[0-9]+' <<< "$PWD"
@anubhava Yes, it works with "pset" followed by one or more numeric digits. Thank you.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.