Mint
Mint

Reputation: 15927

Match folder name from url using regex

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?

Upvotes: 3

Views: 7651

Answers (7)

Adam
Adam

Reputation: 101

Try:

/[a-z0-9_-]+

This would mark all folders in an URL string starting from / including folders having '_' or '-' in the folder name. Hope this would help.

Upvotes: -1

ExpertNoob1
ExpertNoob1

Reputation: 932

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

Upvotes: 0

efg
efg

Reputation:

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;

Upvotes: 1

ghostdog74
ghostdog74

Reputation: 342363

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

Upvotes: 3

Peter Boughton
Peter Boughton

Reputation: 112160

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:

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

Upvotes: 9

Paolo Tedesco
Paolo Tedesco

Reputation: 57202

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.

Upvotes: 3

Nathan de Vries
Nathan de Vries

Reputation: 15511

A regular expression like this should do the trick:

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

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

Upvotes: -1

Related Questions