I would like to write a shell script which will read a list of filenames(with absolute paths) from a file and then determine the just filename component (without the absolute path and the file extension) and the file extension (if any)
But the problem this script craps out when it encounters files with NO extensions e.g. /usr/local/bin/perl
So I have to make it little more robust to handle these scenarios where filenames having no extensions can also exist.
I guess, your script just returns the last field (NF) of the record, which unfortunately doesn't solve my problem. But thanks for responding to my post.
Your solution works fine to get the filename componet (without the extension) and so does mine.
My problem is getting the file extension (especially returning null when there is no extenson per se e.g. /usr/local/bin/perl) That's the part which I am struggling with.
Also, if the file is /tmp/abcde.tar.gz, I would like to return "gz" as the extenion.
while read mLine
do
mNameAndExt=`basename $mLine`
mName=`echo $mNameAndExt | sed 's;\(.*\)\..*;\1;'`
if [ ${#mNameAndExt} -eq ${#mName} ]; then
mExt=''
else
mExt=`echo $mNameAndExt | sed 's/.*\.//'`
fi
done < input_file
Thanks guys for your quick replies! Here is a summary of my testing the various solutions proposed by various people above :
cfajohnson - For some reason your solution returned PATH value for EXT when filename didn't have extension (e.g. /usr/local/bin/perl)
radoulov - Sorry couldn't test your solution because I am using sh and ksh only on our boxes. So can't really tell whether it works
Shell Life - Your solution worked like charm and handled all possible filetypes I have in my test environment
thanks again for helping me out! appreciate it.
So here is the solution I landed up using in my script :
#################################################
#!/bin/sh
for cfilename in `cat filelist.txt | sort -u`
do
filename_w_ext=`basename $cfilename`
filename=`echo $filename_w_ext | sed 's;\(.*\)\..;\1;'`
if [ ${#filename_w_ext} -eq ${#filename} ]; then
file_extension=''
else
file_extension=`echo $filename_w_ext | sed 's/.\.//'`
fi
echo $filename_w_ext
echo $filename
echo $file_extension
done