how to retrieve base name of the file

I have a file name stored in a variable.
A=/bb/data/f233pdb
How can I retrive the base name (f233pdb) and the path (/bb/data/) and assign them to two new variables, so the result will look like this
B=f233pdb
C=/bb/data/

Thansk a lot for any help -A

using bash

# A=/bb/data/f233pdb
# IFS="/"
set -- $A
echo $1

# echo $2
bb
# echo $3
data
# echo $4
f233pdb
# echo $5

       

Check the man for dirname and basename.

$ A=/bb/data/f233pdb
$ c=`basename $A`
$ echo $c
f233pdb
$ d=`dirname $A`
$ echo $d
/bb/data

or U could also..

full_path=/bb/data/f233pdb
pth=$( echo $full_path | sed "s,/[^/]$,," )
file=$( echo $full_path | sed "s,/.
/,," )

Selam

Using variable expansion:

filename=${A##/*/}

path=${A%/*}/
> A=/bb/data/f233pdb
> B=$(echo "$A" | cut -d"/" -f4)
> C=$(echo "$A" | cut -d"/" -f1-3)"/"

> echo $A
/bb/data/f233pdb
> echo $B
f233pdb
> echo $C
/bb/data/

Using cut or IFS, as seen in another post, will only work for a fixed number of sub directories.

The solutions using basename, dirname, sed or variable expansion work for all directory depth.

:slight_smile:

My earlier solution would only work with the example file structure. SO, how about the following:

> cat another_shift 
A=/bb/data/f233pdb
fldb=$(echo $A | tr "/" "\n" | wc -l)
flda=$((fldb-1))
B=$(echo "$A" | cut -d"/" -f"$fldb")
C=$(echo "$A" | cut -d"/" -f1-"$flda")"/"

echo $A
echo $B
echo $C

and now the execution of those commands:

> another_shift 
/bb/data/f233pdb
f233pdb
/bb/data/

To see it working (I substituted on the first variable in the script):

A=/bb/data/another/level/f233pdb

> another_shift 
/bb/data/another/level/f233pdb
f233pdb
/bb/data/another/level/