Friday, November 30, 2007

HowTo: Get the Filename Extension Only

From previous post, we have managed to strip the leading folder path and filename extension. Now, this blog entry is here to cover the reverse approach of my previous basename blog post.

How to manipulate a filename string and return only the filename extension of a file from command line using awk parameters.

For filename with single file extension, removing the leading file name and leaving only the file extension name would be done like so:

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# printf named.conf | awk -F . '{print $2}'
output:
conf
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

For filename with multiple file extension, stripping the leading filename and leaving only the file extension:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# printf named.conf.bak | awk -F . '{print $NF}'
output:
bak
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Another example of removing the leading directory path and leaving only the suffix filename:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# printf /var/cache/named/etc/backup/named.conf.bak | awk -F . '{print $NF}'
output:
bak
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

or using basename would yield to same resulting string
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# basename /var/cache/named/etc/backup/named.conf.bak | awk -F . '{print $NF}'
output:
bak
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

HTH

0 comments:

Sign up for PayPal and start accepting credit card payments instantly.
ILoveTux - howtos and news | About | Contact | TOS | Policy