1

I am writing a bash script and at some point I have $path="things useless things... path/another/files1/useful/path/here"

So I am trying to remove all words and text before "files1" and get the part after files1 (included)

In this example: files1/useful/path/here

I was able to get the part after it but not including files1

How do I achieve this?

3 Answers 3

3

How about (for a file script):

sed -n 's#\(path="\).*/\(files1/[^"]*"\)#\1\2#p' script

Or, if the value is inside a variable:


$ path="things useless things... path/another/files1/useful/path/here"

$ echo "/files1/${path##*/files1/}"

/files1/useful/path/here

2

You can use the ${var#pattern} syntax which will remove the shortest match of pattern from the front of the variable:

$ path="things useless things... path/another/files1/useful/path/here"
$ echo "${path#*another/}" 
files1/useful/path/here

Alternatively, you can use any standard text parsing tool. For instance:

$ newPath=$(sed -E 's|.*(files1/)|\1|'<<<"$path")
$ echo $newPath 
files1/useful/path/here
4
  • the another part is not constant, the files1 is constant though... I can use your solution and re-add the files1 manually, and this what I am currently doing in my script but I was looking for a more elegant way...
    – user206904
    Commented Apr 11, 2021 at 18:52
  • 1
    @user206904 then please edit your question and clarify. Are you looking for something like newPath=$(sed -E 's|.*(files1/)|\1|'<<<"$path")?
    – terdon
    Commented Apr 11, 2021 at 18:54
  • Yes! that solves it!
    – user206904
    Commented Apr 11, 2021 at 18:55
  • @user206904 great, I added that to the answer.
    – terdon
    Commented Apr 11, 2021 at 18:56
2

Since you're using bash you may also use its builtin regex engine:

$ path="things useless things... path/another/files1/useful/path/here"
$ [[ "$path" =~ /files1/.*$ ]] && echo "$BASH_REMATCH"
/files1/useful/path/here

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .