ayush
ayush

Reputation: 14578

shell script to find file name from its path

Hello i want a simple shell script that find the name of the file from a given path of the file. like

$path = "/var/www/html/test.php";

then i want to get value "test" in some variable. Also only .php files are present.I am using bash shell. Thanks

Upvotes: 24

Views: 63007

Answers (4)

Chetan Wadhwa
Chetan Wadhwa

Reputation: 139

Use the basename() function. It is buily in UNIX function

Upvotes: 4

Anjan Biswas
Anjan Biswas

Reputation: 7932

string="/var/www/html/test.php"

oIFS="$IFS"; IFS='/' 
set -A str $string
IFS="$oIFS"

echo "strings count = ${#str[@]}"
len=${#str[@]}
pos=`expr $len - 1`
echo "file : ${str[$pos]}";

Output-

 strings count = 4
 file : test.php

Upvotes: 0

Hogsmill
Hogsmill

Reputation: 1574

Use the built in UNIX command:

basename "/var/www/html/test.php"

Upvotes: 27

Aaron Digulla
Aaron Digulla

Reputation: 328770

Try:

path="/var/www/html/test.php"
name=$(basename "$path" ".php")
echo "$name"

The quotes are only there to prevent problems when $path contains spaces.

Upvotes: 63

Related Questions