Mailinglist Archive: opensuse (686 mails)

< Previous Next >
Re: [opensuse] bash: how to get file extension
On 7/15/2013 5:01 AM, lynn wrote:
Hi everyone
How do I get the mp4 from this?
video_id="Robin Thicke - Blurred Lines ft. T.I.,

I've tried these:



This is it right here. I assure you.

% F=/path/to/foo.blah.txt
% echo "${F##*.}"

ext=$(echo "$video_title" | sed 's/^.*\.//')

The problem is the .'s

I want to ignore all .'s until the final one (not just for this string).

You are saying you want the final answer to _include_ the dot? That is an unreasonably complicated thing to try to do for not enough gain. It's possible with sed, but you're working too hard to figure out that sed/regex syntax, and by forking a process to run sed, also making the computer work too hard.

The simple and practical answer is just to add the dot back in yourself like this:


That is not technically truth right there. If the file has no extension then you will get ext="." which basically claims that the original file name ended with a dot, which is not true.

But since you are probably just looking for a match from a list of known extensions and they all have a leading dot, this should be fine.

Any files that don't have a dot anywhere in the file name, resulting in ext=".", or have a dot somewhere in the middle, resulting in
ext=". Strangelove or : How I Learned to Stop Worrying and Love the Bomb"
Well those files would have failed to match _anyways_ so it doesn't matter.

How to code a particular thing vastly depends on the rest of the job it is a part of. You can make your life unnecessarily hard by trying to get a detail to work a certain way without considering the rest of the context. In this case, I don't think your really need exactly what you asked for and above is good enough, except for two more things:

1 - You probably want to convert ext to all upper or all lower so that you find the matches that YOU and I know are correct even if the computer doesn't. You know that file.Avi is an avi file even though it doesn't match either .avi or .AVI.

For that you can typeset ext so it is all up or all low.
put this near the top of the script, before ext is ever used.
typeset -l ext
typeset -u ext

2 - You probably want to try using file magic (the "file" command) as a fall-back in case $ext was not recognized. Or even other more specialized utilities that use more in-depth knowledge of common media files to identify files by their contents instead of relying on their file names.

Take one of your video files and rename it without the extension.
now run
file "movie title here"

If you had trouble just clipping the ext off of a filename then parsing this output in a script is probably right out, but the info is there.

To unsubscribe, e-mail: opensuse+unsubscribe@xxxxxxxxxxxx
To contact the owner, e-mail: opensuse+owner@xxxxxxxxxxxx

< Previous Next >