Simpom
Simpom

Reputation: 987

Find and replace folder name in path

In my Bash script, I have a variable that contains a path. Let say:

mypath=/a/b/c/d/e

I would like to be able and replace the name of the parent folder of c/d by something else (let say newB), so as to get:

/a/newB/c/d/e

How can I do that? I've tried my best to combine cut, sed and awk but I'm getting awfully long commands without getting the desired result.

Upvotes: 1

Views: 700

Answers (2)

choroba
choroba

Reputation: 241848

Use parameter expansion.

#!/bin/bash
mypath=/a/b/c/d/e
parent=${mypath%/c/d/*}
suffix=${mypath#*/c/d/}
grandparent=${parent%/*}

newpath=$grandparent/newB/c/d/$suffix
echo $newpath

With extglob, you can use substitution, which simplifies the script:

#!/bin/bash
mypath=/a/b/c/d/e

shopt -s extglob
pattern=+([^/])/c/d
newpath=${mypath/$pattern/newB/c/d}
echo $newpath

Upvotes: 1

heemayl
heemayl

Reputation: 42007

With sed:

sed -E 's#^(.*/)[^/]+(/c/d/)#\1newB\2#'
  • (.*/) matches upto the / (and put in captured group 1), followed by one or more characters that are not / ([^/]+)

  • The second captured group, (/c/d/), matches /c/d/ literally

  • In the replacement the parent of /c/d/ is replaced with newB and the captured groups are kept expectedly

Example:

% mypath=/a/b/c/d/e                               

% sed -E 's#^(.*/)[^/]+(/c/d/)#\1newB\2#' <<<"$mypath"
/a/newB/c/d/e

Upvotes: 1

Related Questions