Last Updated: November 28, 2016
·
557
· jasny

How to get a file extension in several languages

How to get a file extension in Bash:

ext=${file_name##*.}
name=${file_name%.*}

How to get a file extension in PHP:

$ext = pathinfo($file_name, PATHINFO_EXTENSION);

How to get a file extension in Perl:

my $ext = ($file_name =~ m/([^.]+)$/)[0];

How to get a file extension in Ruby:

ext = File.extname(file_name)

How to get a file extension in Python:

import os
ext = os.path.splitext(file_name)[1]

How to get a file extension in JavaScript:

var ext = /\.(\w+)$/.exec(file_name)[1]

How to get a file extension in C#

FileInfo f = new FileInfo(“test.txt”);
string ext = f.Extension; # ext = txt

How to get a file extension in D

char[] ext =std.path.getExt(fnam)