Search code examples
bashsedpathecho

Bash: How to remove certain parts of the path using a defined variable


I need help with Bash scripting.

What I am trying to do is to remove certain part of a path using a defined variable.

Let's say we have a path:

path= /path/that/I/want/part/that/I/do/not

And I have a variable defined as:

x="want"

This variable "x" can be anything, e.g. x="that", or x="I", but in this example, let's say x="want".

So I want look into the "path" variable and search where the "x" variable is. Then remove everything in the "path" variable that appears after the "x" variable.

So in this example, my expected output is

path= /path/that/I/want/

I have tried using

echo $path | sed 's/\($x\).*/\1/g'

But it did not work.

Please help

Thank you so much

Tommy


Solution

  • Replace ' with "

    Replace / with :

    x="want"
    path=/path/that/I/want/xxxxxxxxxx
    echo $path | sed "s:\($x\).*:\1:g"