Fetching just the matching pattern

Hi Everybody,

I would like you to help me with the following problem.

Given is a path to a file like this:

/root/DIR/subdir/file.dat

Having this path I would like to grep/sed or whatever the directory string
that matches the following pattern '[A-Z][A-Z][A-Z]'.

I just need the matching directory string not the whole line.

f.ex. Let's assume I am in the mentioned directory "subdir"

pwd | grep '[A-Z][A-Z][A-Z]'

---> this command prints the full path but I just need the DIR part, because it matches my pattern

! the option -o doesn't exist on my machine

Your help would be very much appreciated.

Thanks in advance,

hoschi

you can use sed search and replace to just print the match, you just have to put the pattern in parentheses, and then reference the match in the replace part with a \1

pwd | sed 's/.*\(pattern\).*/\1/'

the ugly part is that you have to escape the parentheses with backslashes.

There is probably a better way, but this is short, and works like a charm

Thanks for your reply.

I assume sed is starting to look for the pattern from the beginning of the
input stream. How can I make sure that just the first occurrence of the searched pattern is being printed?

f.ex. input stream would be something like

/root/FIRSTMATCH/subdir/SECONDMATCH

Thanks in advance,

hoschi

But there aren't any multiple occurrences in your input stream.

"FIRSTMATCH" occurs only once, and "SECONDMATCH" occurs once as well. They are two different strings.

tyler_durden

Hope this will be helpful for you.

$ echo /root/DIR/subdir/DIR/file.dat|grep -o "[A-Z][A-Z][A-Z]"|head -1
DIR

Regards,

Ranjith

Thanks ranjithpr, but as I stated in my very first comment. The grep version I am using doesn't provide me with an "o" option, otherwise I would have used it.

---------- Post updated at 10:14 AM ---------- Previous update was at 10:06 AM ----------

I found a nice solution for my problem:

Variable=`echo ${listofdirectories} | grep data | awk -F"/" '{print $5}' | cut -d"/" -f1`