prosseek
prosseek

Reputation: 190759

Extracting path element to make a string in bash

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?

Upvotes: 2

Views: 455

Answers (3)

Josh Cartwright
Josh Cartwright

Reputation: 801

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

Upvotes: 1

Vijay
Vijay

Reputation: 67221

echo $PATH|awk -F"/" '{print $(NF-1)"_"$NF"_HELLO";}'

Upvotes: 2

Anton Kovalenko
Anton Kovalenko

Reputation: 21507

Use basename and dirname:

parent=$(dirname "$input")
output=$(basename "$parent")_$(basename "$input")_HELLO

Upvotes: 2

Related Questions