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
: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
Simplest Way to Build Dotnet Sdk Project Requiring Net461 on Macos
How to Send a Mail with a Message in Unix Script
Linux: Proc/Net/Sockstat Tcp Mem More and More Larger
What Does "Private_Dirty" Memory Mean in Smaps
Linux: Move 1 Million Files into Prefix-Based Created Folders
Sharing Stdout Among Multiple Threads/Processes
Remove a List of Words from Filename
Docker - Is It Safe to Switch to Non-Root User in Entrypoint
Scale PDF to Add Border for Printing Full Size Pages
Bash Tries to Execute Commands in Heredoc
Setting Environment Variable with Leading Digit in Bash
What Does "Private_Dirty" Memory Mean in Smaps
Sending Command to Process Using /Proc
Would It Be Possible to Read Out Physical Keyboard Strokes in Node.Js