I need the first three folder names from the string "/dp-ml-training/training/babyweight/trainer/notebooks/babyweight.ipynb"
hence obtaining "/dp-ml-training/training/babyweight"
Or equivalently, I need the file path before the folder "/trainer"
that is "/dp-ml-training/training/babyweight"
How can I achieve this in bash with sed/awk/grep/cut etc? Request your help. Thanks in Advance!
CodePudding user response:
You can use the "Parameter Expansion" of Bash.
path="your path"
echo ${path%%/trainer*} # remove string from '/trainer' to end
CodePudding user response:
Assuming that your string is stored in the variable s
, you could do a
if [[ $s =~ ^/[^/]*/[^/]*/[^/]* ]]
then
head=${BASH_REMATCH[0]}
else
head=$s
fi