Link to home
Start Free TrialLog in
Avatar of Swaminathan K
Swaminathan KFlag for India

asked on

Need help on Unix

Hi ,

I have write a shell script which extracts the folder info from an environmental variable.
BASE_DIR="/home/app/goo/collecto/output" is the folder path stored in the BASE_DIR variable.

I need to extract /home/app/goo/collecto from the BASE_DIR variable, below is the commands which I have used , but Iam not getting the actual result

pd= `echo $BASE_DIR | gawk '{print substr($0,1,match($0,"collecto"))}'

the output Iam getting is /home/app/goo/c and not /home/app/goo/collecto.
kindly help me in this regard

thanks in advance
sam
Avatar of ozo
ozo
Flag of United States of America image

#!/bin/bash
BASE_DIR="/home/app/goo/collecto/output"
pd=${BASE_DIR%/*}
pd= `echo $BASE_DIR | gawk '{{match($1,"Collecto");print substr($0,1,RSTART+RLENGTH))}'
pd=$(dirname $BASE_DIR)

pd=$(echo $BASE_DIR | awk -F"collecto" '{print $1 FS}')

pd=$(echo $BASE_DIR | sed 's/\(^\/.*collecto\).*/\1/')
What would you want $pd to contain if "collecto" did not occur in $BASE_DIR
or "collecto" occurred multiple times in  $BASE_DIR, or if "collectorship" occurs in $BASE_DIR
or if there were more levels of directories under collecto?
Some of the suggested solutions produce different results in those cases.
Avatar of Swaminathan K

ASKER

hi ozo

if collecto is not present in $BASE_DIR it should throw an error and exit,  if collecto appears multiple times in basedir , the one after goo should be used , no collectorship should not be selected , it should error out , even if there are more levels of directories uner collecto , the variable pd should contain only the path upto collecto.
ASKER CERTIFIED SOLUTION
Avatar of woolmilkporc
woolmilkporc
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
hi woolmilkproc

question 1: when collecto is the last element then , I have to store the entire path in my pd variable.
Question 2: if only collecto is present then store the entire path in pd variable upto collecto.
OK. A bit more code, but here you go:

if echo "$BASE_DIR" | grep -qw "collecto"; then
   SEP="collecto"
   if echo "$BASE_DIR" | grep -q "goo/collecto"; then
      SEP="goo/collecto"
   fi
    pd=$(echo "$BASE_DIR" | awk -F"$SEP" '{print $1 FS}')
  else
     echo "Error. Invalid Path!"
     exit 22
fi
thanks , that really met my requirement