2

I googled for several hours and could not find a solution for the following issue (at least I did not find one I could understand and adapt).

My cwd is:

/home/ubuntu/data/modelling/Iamvariable/Var1/PRODUCTION/ANALYSIS/Var2/DIHEDRALS

and I need to extrakt the "text" behind Var1 and Var2.

I would like to scan the pwd output from right to left since the file path starting could change but the path starting after Iamvaribale will stay always the same. By means of number of elements in path and except Iamvaribale (and of course Var1 and Var2) also the folder names will stay the same.

How can I achieve this in a bash sricpt?

Var1 = 
Var2 =

edit:

/home/ubuntu/data/modelling/Iamvariable/Var1/PRODUCTION/ANALYSIS/Var2/DIHEDRALS

basically everything in capital letters is fixed. If there is no easy solution where

/home/ubuntu/data/modelling 

is not fixed this is OK to be set as fixed. But it would be better to have it not fixed, to have it more flexible.

0

1 Answer 1

2

Use parameter expansion:

#!/bin/bash
path=/home/ubuntu/data/modelling/Iamvariable/Var1/PRODUCTION/ANALYSIS/Var2/DIHEDRALS
var1=${path%/PRODUCTION/ANALYSIS/*}
var1=${var1##*/}
echo "$var1"

var2=${path#*/PRODUCTION/ANALYSIS/}
var2=${var2%/*}
echo "$var2"

# removes from the beginning, % from the end of the parameter. Doubling the character means the largest possible string will be removed.

8
  • Could you explain further how does var1=${var1%%/*} work? Thanks :)
    – M. Becerra
    Jan 15, 2018 at 10:49
  • Thanks for your quick answer! For Var 2 I understand that this will work out but for Var1 I don't. How can search for something whitch is variable. Maybe I translated wrong. With that expression I meant that on this position the folder could be namend as anything. Jan 15, 2018 at 11:06
  • In theory we could read out what is after modelling and put this temporary var as search for var1. However I would like to have it, if possible, more robust since every thing before "Iamvarible" could be changed Jan 15, 2018 at 11:12
  • Can you give some examples? What parts of the path are fixed?
    – choroba
    Jan 15, 2018 at 12:09
  • I added examples above. Jan 15, 2018 at 12:33

Not the answer you're looking for? Browse other questions tagged or ask your own question.