extracting a field from directory path ??????

Hi

I'll be getting a directory path as the input to the script.
E.g. 1 abc/fsg/sdfhgsa/fasgfsd/adfghad/XXX/fhsad
e.g. 2 sadfg/sadgjhgds/sd/dtuc/cghcx/dtyue/dfghsdd/XXX/qytq

This input will be stored in a variable.

My query is how to extract the field in a variable VAR which occurs just before XXX
Please note that XXX position is not fixed in the directory path.

Kindly provide the code.

Thanks and Best Regards

Let me get this straight. You want the third last entry in the path, right ?

Use awk (or similar tool) with / as a field separator and match the third pattern from the end.

No. i want the field just before XXX.

I want the field just before XXX wherever XXX is in the path. Position of XXX not fixed.

Oh. So XXX is not a placeholder but an actual text.

Is this a homework assignment?

I need it urgent. not a homework

The whole thing is a DIRECTORY path. XXX is a fixed folder name.

sed -n -e "s+.*/\([^/]*\)/XXX.*+\1+p" input.txt

The whole directory path is in a variable. Not in a file. How can we modify the below?

Thanks

var="/abc/fsg/sdfhgsa/fasgfsd/adfghad/XXX/fhsad"
echo $var |awk ' BEGIN{FS="/"}
                 {
                        for(i=1;i<=NF;i++){
                                if ($i == "XXX") {
                                        print $(i-1)
                                        next
                                }

                        }
                 }'

Thanks to all of you !!!!

YOUR MAKING IT TOO HARD. Use Korn/Bash built-in variable operators.
##
#EXPRESSION RESULT
#/home/david/waffen/long.file.name
#${path%%.} /home/david/waffen/long
#${path%.
} /home/david/waffen/long.file
#${path} /home/david/waffen/long.file.name
#${path#//} /david/waffen/long.file.name
#${path##/
/} long.file.name
#${path##*/} long.file.name
###

PATH1=/A/B/C/D/XXX/E/F/G
PATH2=/A/B/C/XXX/E

echo "${PATH1%%/XXX/}"
echo "${PATH2%%/XXX/
}"

OUTPUT:
$ echo "${PATH1%%/XXX/}"
/A/B/C/D
$ echo "${PATH2%%/XXX/
}"
/A/B/C

-David

I think OP only wants D for PATH1, and C for PATH2. can you change that thanks.

PATH1=/A/B/C/D/XXX/E/F/G
PATH2=/A/B/C/XXX/E

# Chop everything from /XXX/ to end
VAR1=$(echo "${PATH1%%/XXX/}")
VAR2=$(echo "${PATH2%%/XXX/
}")

# Chop leading path, similar to `basename` unix command
echo ${VAR1##/} # result is D
echo ${VAR2##
/} # resule is C

Cheers -
David