Chris Bolton
Chris Bolton

Reputation: 2314

Find last word in path and remove brackets with regex using bash

I have done lots of searching on SO and google.

I am using a regex tester like Regex 101.

The test string is [../../dvl/namespaces/my-namespace-1/notterminating]

The regex I am using is .*\/([^\/]*)[\[\]']+.

What I am trying to do (returns empty):

$ param="[../../dvl/namespaces/my-namespace-1/notterminating]"
$ echo $param | grep ".*\/([^\/]*)[\[\]']+"

I have tried different options with grep by adding different flags like -o, -e, etc. I have tried "${param}.*\/([^\/]*)[\[\]']+". However, I have been unsuccessful at getting bash to recognize my regex.

Upvotes: 1

Views: 61

Answers (3)

ashish_k
ashish_k

Reputation: 1581

Using sed:

echo "$param" |sed -r -n 's,.*\/(.*)\],\1,p'

output:

notterminating

Upvotes: 2

anubhava
anubhava

Reputation: 786289

Without using any external tool you can do this in pure bash with IFS:

IFS='/\[\]' read -ra arr <<< "$param" && echo "${arr[-1]}"

notterminating

Otherwise you may use this simple sed:

sed 's~.*/~~' <<< "${param//[]]}"

notterminating

Or by using awk:

awk -F '[][/]' '{print $(NF-1)}' <<< "$param"

notterminating

Upvotes: 2

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627536

You may use sed:

sed -n "s@.*/\([^]['/]*\).*@\1@p" <<< "$param"

See an online demo

Details

  • .* - matches 0+ chars
  • / - / char
  • \([^]['/]*\) - Group 1: any 0+ chars other than ], [, ' and /
  • .* - any 0+ chars.

This way, the whole string is replaced with the Group 1 value, and only that value remains as -n suppresses default line output and p prints the result.

Upvotes: 2

Related Questions