Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

print dir path after matching its name with wildcards

Tags:

path

awk

wildcard

Have been stuck with this little puzzle. Thank you in advance for helping.

I have a directory path and would like print its path after match.

like

echo /Users/user/Documents/terraform-shared-infra/services/history_book_test | awk -F "terraform-|tfRepo-" '{print $(NF)}'

echo /Users/user/Documents/tfRepo-shared-infra/services/history_book_test | awk -F "terraform-|tfRepo-" '{print $(NF)}'

output:

shared-infra/services/history_book_test

shared-infra/services/history_book_test

When i try to add wildcard in terraform-* it doesn't work.

I would like to print path after match with terraform-* or tfRepo*. Like:

services/history_book_test
services/history_book_test/../.. so on.

with sed:

echo /Users/user/Documents/terraform-shared-infra/services/history_book_test | sed 's|.*terraform.\([^/]*\)/.*|\1|'
shared-infra

Have tried different ways with awk and grep but no luck. Any leads or idea that I can try. Please.

Thank you.

like image 339
Adi Avatar asked Dec 06 '25 13:12

Adi


1 Answers

You're confusing regular expressions with globbing patterns. Both have wildcards and look similar but have quite different meanings and uses. regexps are used by text processing tools like grep, sed, and awk to match text in input strings while globbing patterns are used by shells to match file/directory names. For example, foo* in a regexp means fo followed by zero or more additional os while foo* in a globbing pattern means foo followed by zero or more other characters (which in a regexp would be foo.*). So never just say "wildcard", say "regexp wildcard" or "globbing wildcard" for clarity.

This might be what you're trying to do, using a sed that has a -E arg to enable EREs, e.g. GNU or BSD sed:

$ sed -E 's:.*/(terraform|tfRepo)-[^/]*/::' file
services/history_book_test
services/history_book_test

or using any awk:

$ awk '{sub(".*/(terraform|tfRepo)-[^/]*/","")} 1' file
services/history_book_test
services/history_book_test

Regarding your attempt with sed sed 's|.*terraform.\([^/]*\)/.*|\1|' - if you're going to use a char other than / for the delimiters, don't use a char like | that's a regexp or backreference metachar as at best that obfuscates your code, pick some char that's always literal instead, e.g. :.

like image 181
Ed Morton Avatar answered Dec 08 '25 07:12

Ed Morton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!