I am trying to get the file extension with file names that could contain multiple dots using shell scripting. I want to find a way using the sed command.
Example Filenames:
one.dat
one.dat.002
Results:
dat
I would like to return dat in both instances using the sed command. How can I achieve this?
sed 's/^.\.//' = just returns the last three (dat and 002 respectively)
sed 's/\(.*\)\../\1/' = returns one and one.dat respectively
I am new to this type of programming so I don't know the full details. I currently have a job in Appworx (UC4 Job Scheduling) that calls a shell script (#!/bin/sh) which processes information (copying, removing files, etc). Instead of hardcoding .dat (in case later on it becomes .DAT or something else) in for the file name, I am trying to grab the extension to use it later on in my code to avoid any hard coding that may need changing later.
Below is just a sample of the code I currently have in place:
for f in $2.DAT*
do
if [ -s $f ]; then
scp -p $f $3/$2.DAT
echo "Banner Admin job runs here"
sleep 60
rm $3/$2.DAT
$2 and $3 are parameters passed into the shell script.
$2's value would be one
$3's value is a target directory
Okay, that's what I thought. I should have left my original post there after all. :o
Anyway, given files in the current dir like this and assuming that the extension is after the first period:
$ ls
efs one.dat one.dat.002 one.txt two
$
This code reads the current file list a file at a time then based on an Input Field Separator of "." parses the name into variables, which are then printed out. This should help you.
#!/bin/sh
ls|while IFS="." read filename extension the_rest
do
echo "$filename \c"
if [ -n "$extension" ]; then
echo "[$extension] $the_rest"
else
echo "[no extension]"
fi
done
exit 0
Output:
efs [no extension]
one [dat]
one [dat] 002
one [txt]
two [no extension]