views:

1107

answers:

6

I want to match just the folder name that a file is in,

eg:
pic/2009/cat01.jpg
pic/2009/01/cat02.jpg

I want to just match what I put in bold.

So far I have this:

[^/]*/

Which will match,
pic/2009/cat01.jpg

Any idea?

+4  A: 

Not sure I understand what you're asking, but try this:

[^/]+(?=/[^/]+$)

That will match the second to last section only.


Explanation:

(?x)     # enable comment mode
[^/]+    # anything that is not a slash, one or more times
(?=      # begin lookahead
  /      # a slash
  [^/]+  # again, anything that is not a slash, once or more
  $      # end of line
)        # end lookahead

The lookahead section will not be included in the match (group 0) - (you can omit the lookahead but include its contents if your regex engine doesn't do lookahead, then you just need to split on / and get the first item).

Hmmm... haven't done bash regex in a while... possibly you might need to escape it:

[^\/]+\(?=\/[^\/]+$\)
Peter Boughton
Thanks as-well, I have been using this site for a while but only just registered today and I am blown away at how fast I got my solution. Altho this didn't work for me using sed: sed -E 's/[^\/]+(?=\/[^\/]+$)//g' Error: sed: -e expression #1, char 26: Invalid preceding regular expression [^\/]+\(?=\/[^\/]+$\) does nothing, it didn't change anything. But the top one you posted ""[^/]+(?=/[^/]+$)"" does work as a regex and I may use it latter on with php.PS, Thanks for detailed expiation of what each part does, I can never understand what each part does.
Mint
A: 

A regular expression like this should do the trick:

/\/([^\/]+)\/[^\/]+$/

The value you're after will be in the first capture group.

Nathan de Vries
The solution provided by Peter Boughton (http://stackoverflow.com/questions/1130016/match-folder-name-from-url-using-regex/1130024#1130024) is much better.
Nathan de Vries
mmm yes this seems to work, but how to I specify which which group it should use? (im using sed, or should I use awk...)
Mint
+1  A: 

Without using a regular expression:

FILE_NAME="pic/2009/cat01.jpg"
basename $(dirname $FILE_NAME)

dirname gets the directory part of the path, basename prints the last part.

Paolo Tedesco
Thanks, that works perfect.It didn't have to be a regex, thats just what I thought you would use for the job.
Mint
+1  A: 

without the use of external commands or regular expression, in bash

# FILE_NAME="pic/2009/cat01.jpg"
# FILE_NAME=${FILE_NAME%/*}
# # echo ${FILE_NAME##*/}
2009
ghostdog74
+1  A: 

My lazy answer:

for INPUTS in pic/2009/cat01.jpg pic/2009/01/cat02.jpg ; do
  echo "Next path is $INPUTS";
  LFN="$INPUTS";
  for FN in `echo $INPUTS | tr / \ ` ; do
    PF="$LFN";
    LFN="$FN";
  done;
  echo "Parent folder of $FN is $PF";
done;
A: 

echo pic/2009/cat01.jpg | awk -F/ '{print $(NF-1)}'

ExpertNoob1