Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing everything but filename extension [duplicate]

Tags:

linux

bash

Let's say I have a string:

x=file.tar.sh

I know how to remove everything but last n-characters. Like this (removing everything but last 3 characters:

${x: -3}

But this doesn't work for files with different suffix lengths. (len .tar != len .sh)

I would tackle this by removing everything until the last dot. I've tried this:

${x##.}

This removes the longest matching until "." but somehow it just returns the full string without removing anything?

like image 338
mythic Avatar asked May 11 '15 15:05

mythic


People also ask

What happens if you remove a file extension?

In Windows, if you delete a file extension, Windows no longer knows what to do with that file. When you try to open the file, Windows will ask you what app you want to use. If you change an extension—say you rename a file from “coolpic. jpg” to “coolpic.

What does it mean if a file has multiple extensions?

More than one extension usually represents nested transformations, such as files. tar. gz (the . tar indicates that the file is a tar archive of one or more files, and the . gz indicates that the tar archive file is compressed with gzip).

How do you remove a filename extension in Unix?

You should be using the command substitution syntax $(command) when you want to execute a command in script/command. name=$(echo "$filename" | cut -f 1 -d '. ')


1 Answers

Try this:

x=file.tar.sh
echo ${x##*.}

This will print sh

If you want to get tar.sh, then:

echo ${x#*.}

Here * matches any set of characters before the occurrence of .

like image 178
Jahid Avatar answered Nov 01 '22 16:11

Jahid