Reading extension of files

Hi,
I need a command to read extension of files. Could anyone please help me?

ls -l |grep *.tgz

this will grep for the particular extension you need.

if I get your question right... then you need to read the extn of all the files? Am I correct?

If so, above code will be of less help.

You can try this:

 
var1=abcd.xyz
var2=$(echo $var1 | sed 's/.*\(.\{3\}\)$/\1/')
echo $var2

What this will to is read the last three characters of your file name[assuming that your file extn is of 3 char only]

Many Thanaks,

abc=test.txt
ext=$(echo $abc|awk -F "\." '{print $2}')

print $ext;---> txt

If you have to cut extension from all the files, U can using loop to list out all the file names, then inside that loop , u can use it.

below could be more generic.

/home->echo "myfile.tmp" | sed '/\.[^.]*$/ s/.*\.\([^.]*$\).*/\1/p'
tmp
/home->echo "myfile.tmp2" | sed '/\.[^.]*$/ s/.*\.\([^.]*$\).*/\1/p'
tmp2
/home->echo "myfile.tmp2.tmp345" | sed '/\.[^.]*$/ s/.*\.\([^.]*$\).*/\1/p'
tmp345

Hi Anchal,

Can you please explain the code above.....

Thanks in advance.

echo "file_name.sh" |  sed 's/.*\.\(.*\)/\1/' 

will work for all.

it is just a regex.
first of all i m modifying the solution.
pl refer to this

it is searching for the pattern like this..

.* - anything
\. - literal dot.
[^.]*$ - anything after dot except dot at the end.
\(..\) - save the regex found
\1 - replace the regexp saved.

in previous solution i was first searching for the pattern.

Why do you use an external command when you can do it in the shell?

filename=file_name.sh
extension=${filename##*.}
Why do you use an external command when you can do it in the shell?

since i am not good in bash programming. Have to learn a lot :rolleyes::rolleyes:

cfajohnson is right! You can even do it with tcsh:

set filename = file_name.xyz
echo $filename:e
ls | sed 's/.*\.//'

It's not just bash; it's the standard Unix (a.k.a POSIX) shell.

this is simple to understand

echo "myfile.tmp" | awk -F"." '{print $NF}'
   or 
echo "myfile.tmp2.tmp345" | sed 's/.*\.//'