How to Get the Last Dir from a Path in a String

How to get the last dir from a path in a string

Use basename

basename('Home/new_folder/test');
// output: test

As a side note to those who answered explode:

To get the trailing name component of a path you should use basename!
In case your path is something like $str = "this/is/something/" the end(explode($str)); combo will fail.

get last directory from a string

You might be interested in the command basename :

$ basename /dir1/dir2/dir3
dir3

man basename :
Print NAME with any leading directory components removed.

This can be combined with find as :

$ find path -maxdepth 2 -type d -name "*abc" -exec basename {} \;

or you can avoid basename and just pipe it to awk as :

$ find path -maxdepth 2 -type d -name "*abc" | awk -F'/' '{print $NF}'

But if you really want to avoid anything and just use find you can use the printf statement of find as :

$ find path -maxdepth 2 -type d -name "*abc" -printf "%f\n"

man find: %f File's name with any leading directories removed (only the last element).

How can I get the last folder from a path string?

You can do:

string dirName = new DirectoryInfo(@"C:\Users\me\Projects\myProject\").Name;

Or use Path.GetFileName like (with a bit of hack):

string dirName2 = Path.GetFileName(
@"C:\Users\me\Projects\myProject".TrimEnd(Path.DirectorySeparatorChar));

Path.GetFileName returns the file name from the path, if the path is terminating with \ then it would return an empty string, that is why I have used TrimEnd(Path.DirectorySeparatorChar)

How to get only the last part of a path in Python?

Use os.path.normpath, then os.path.basename:

>>> os.path.basename(os.path.normpath('/folderA/folderB/folderC/folderD/'))
'folderD'

The first strips off any trailing slashes, the second gives you the last part of the path. Using only basename gives everything after the last slash, which in this case is ''.

PHP: Get last directory name from path

Easiest way would be to use basename($yourpath) as you can see here: http://php.net/basename

How to get last & second last folder name from path using php?

Here's a simple option using basename and dirname:

$path = 'Home/Gallery/Images/Mountains';
$lastFolder = basename($path);
$secondToLastFolder = basename(dirname($path));

Demo

Get the (last part of) current directory name in C#

You're looking for Path.GetFileName.

Note that this won't work if the path ends in a \.

Return last directory in a path

var path='first/second/third/';
var path2 = path.split('/');
path2 = path2[path2.length-2];

-2 because the last one is empty because of the last slash.

In Python, how should one extract the second-last directory name in a path?

'/cvmfs/atlas.cern.ch/repo/sw/ASG/AnalysisTop/2.0.24/RootCore'.split('/')[-2]


Related Topics



Leave a reply



Submit