Bash script for splitting a filename, extension and path from fullpath

Call the function split_filenames with the first argument as the full filename with path. Alternately, set the variable fullfile to this value.

#!/bin/bash

split_filenames() {
# echo "Called with Arg: $1"
if [ ! "$1" = "" ]
then
fullfile=$1

fi
# echo I got this filename for processing $fullfile
filename=$(basename "$fullfile")
fname=$(basename "$fullfile")
nameonly=${filename%.*}
ext=${fname##*.}

echo "filename $filename"

filename=${fullfile%.*}
pathonly=${fullfile%/*}

if [ "$pathonly" = "$fullfile" ]
then
pathonly="$pat"
fi

echo "Path $pathonly"
echo "Name $nameonly"

chkper=$(echo $fullfile | grep -c "\.")
# echo "Number of periods:$chkper"

if [ ! "$chkper" = "0" ]
then
echo "Extension $ext"
else
echo "No extension"
fi

#out_file=$pathonly/$nameonly"_signed."$ext

}

for i in ~/Dropbox/SSH\ Keys/*
do
echo
echo Path and Name: $i
split_filenames "$i"
#cp "$i" testssh/
done[/code]
In the example, the main event calls the function from a loop which cycles through all the files in the specified directory.


You are reading this post on Joel G Mathew’s tech blog. Joel's personal blog is the Eyrie, hosted here.