Bash Questions

I am writing a Bash script that needs to get part of the current directory path. Let's say the current directory is /cat/dog/bird/mouse/ant. I know that the part that I want is between "bird/" and "/ant". In this case, I would want to set a variable to "mouse".

If the current directory were /cat/dog/bird/giraffe/ant I would want to set a variable to "giraffe" because I want what is between "bird/" and "/ant".

I know that "bird/" and "/ant" are part of the path, but I can't alway predict what will come before that. So, regardless of whether the current directory is /cat/dog/bird/giraffe/ant or /rat/bird/giraffe/ant I want to get the "giraffe" part.

I know I can capture the current directory in my script by doing this: currdir=`pwd`
But I'm not sure what to do afterwards.

I know there is a "cut" command, but that typically works on files, not variables. And I don't know which field number to ask cut to return, because it will vary depending upon what the current directory is.

Would I use awk for this?

Is it frowned upon to use awk within a Bash script? I hesitate to use awk because it seems cleaner to use native Bash rather than embed another whole language in my scripts. What is the conventional wisdom about this? Should I use other languages like awk and Perl in a Bash script? Shouldn't I pick one scripting language and stick to it?

many ways to skin that cat:

echo '/cat/dog/bird/giraffe/ant' | sed 's#.*/bird/\([^/][^/]*\)/ant.*#\1#g'
1 Like

Wow. You did sed on a string by just piping echo through it. I didn't know you could do that. I thought sed was for files only.

How do I figure out what the s# and [^/] and 1#g mean? Is that regular expression syntax?

#.*/bird/\([^/][^/]*\)/ant.*#

.*/bird/         - anything followed by '/bird/'
\([^/][^/]*\) - followed a FIRST 'capture' of: anything, but '/' repeated 0 or more times
/and.*          - followed by '/ant' and anything '.*'


#\1#g
\1                 - substitute the above pattern with the FIRST capture
g                  - do it Globally (g) for all matching pattern on a single line


#\1#g'

read 'man sed' and this link.

1 Like

Using built-in bash parameter expansion:

d='/cat/dog/bird/giraffe/ant'; d=${d#*bird/}; echo ${d%/ant*}
giraffe

See man bash -> 'Parameter Expansion' for more infos

1 Like