How to select First two directory in from path name?

Can somebody help me on below question

I have path and i want to select first two directory name in variable how we can do this.

/Myname/xyz/yourname/abc/somebodyname

i want to select /Myname/xyz in variable.

Quick help will be appriciated.

Thanks in advance

Regards,
Kumar

$ var='/Myname/xyz/yourname/abc/somebodyname'

$ echo "$var"|sed -n 's:^\(/[^/]\{1,\}/[^/]\{1,\}\).*:\1:p'
/Myname/xyz

Dear elixir,
how we can assign the output "/Myname/xyz" to variable.
i am able to print it but not able to assign to variable. its giving error "Var is Directory"

newvar=$(echo "$var"|sed -n 's:^\(/[^/]\{1,\}/[^/]\{1,\}\).*:\1:p')
1 Like

with awk..

var='/Myname/xyz/yourname/abc/somebodyname'

dir_path=$(echo "$var" | awk -F "/" '{print "/"$2"/"$3}')

Can somebody help to me to get the required value from below path

./mydata/abc/youdata/xyz/OTHERDATA/zsoddata_testsod_labl_20120111_1.zip

i want to fetch the "testsod" from below path and file name..

Kind Regards,
kumar

var=$( echo "./mydata/abc/youdata/xyz/OTHERDATA/zsoddata_testsod_labl_20120111_1.zip" | awk -F_ ' { print $2 } ' )

Dear Bipinajith,
Thanks for reply..
i just forgot to add
that the filepath can be as belo
"./mydata/abc/you_data/xyz/OTHER_DATA/zsoddata_testsod_labl_20120111_1.zip"

and i need "testsod" in variable

Regards,
Kumar

---------- Post updated at 09:46 AM ---------- Previous update was at 09:43 AM ----------

Dear Bipinajith,
Thanks for reply..
i just forgot to add
that the filepath can be as belo
"./mydata/abc/you_data/xyz/OTHER_DATA/zsoddata_testsod_labl_20120111_1.zip"

and i need "testsod" in variable

Regards,
Kumar

echo "./mydata/abc/you_data/xyz/OTHER_DATA/zsoddata_testsod_labl_20120111_1.zip" | sed 's#.*/[^_][^_]*_\([^_][^_]*\).*#\1#'
1 Like

It would be greate if you can explain how it works..

echo "./mydata/abc/you_data/xyz/OTHER_DATA/zsoddata_testsod_labl_20120111_1.zip" | awk -F"/" ' { split($NF,a,"_"); print a[2]; } '