2

I'd like to synthesize a string from a directory name in bash. I need to extract the last two path names to make a string.

For example, with an input /a/b/c, I want to make "b_c_HELLO".

How can I do that with bash?

3 Answers 3

2

Use basename and dirname:

parent=$(dirname "$input")
output=$(basename "$parent")_$(basename "$input")_HELLO
2
echo $PATH|awk -F"/" '{print $(NF-1)"_"$NF"_HELLO";}'
1

A pure bash implementation leveraging Parameter Expansion:

input="a/b/c"
tmp="${input%%/*/*}"
tmp="${tmp#$tmp/}"
output="${tmp/\//_}_HELLO"

Also, see http://mywiki.wooledge.org/BashFAQ/100

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.