Take The Last Part of The Folder Path in Shell

Take the last part of the folder path in shell

You're right--it's a quick command:

basename "$PWD"

Get last dirname/filename in a file path argument in Bash

basename does remove the directory prefix of a path:

$ basename /usr/local/svn/repos/example
example
$ echo "/server/root/$(basename /usr/local/svn/repos/example)"
/server/root/example

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 to extract directory path from file path?

dirname and basename are the tools you're looking for for extracting path components:

$ VAR='/home/pax/file.c'
$ DIR="$(dirname "${VAR}")" ; FILE="$(basename "${VAR}")"
$ echo "[${DIR}] [${FILE}]"
[/home/pax] [file.c]

They're not internal bash commands but they are part of the POSIX standard - see dirname and basename. Hence, they're probably available on, or can be obtained for, most platforms that are capable of running bash.

How to split path by last slash?

Use basename and dirname, that's all you need.

part1=$(dirname "$p")
part2=$(basename "$p")

Extract the last directory of a pwd output

Are you looking for basename or dirname?

Something like

basename "`pwd`"

should be what you want to know.

If you insist on using sed, you could also use

pwd | sed 's#.*/##'

Linux Shell Script cut last part of variable which contains a path

$ read path
this/is/the/path/I/need
$ directory=$(basename $path)
$ echo $directory
need
$


Related Topics



Leave a reply



Submit