268

What's wrong with the following code?

name='$filename | cut -f1 -d'.''

As is, I get the literal string $filename | cut -f1 -d'.', but if I remove the quotes I don't get anything. Meanwhile, typing

"test.exe" | cut -f1 -d'.'

in a shell gives me the output I want, test. I already know $filename has been assigned the right value. What I want to do is assign to a variable the filename without the extension.

codeforester
  • 39,467
  • 16
  • 112
  • 140
mimicocotopus
  • 5,280
  • 4
  • 22
  • 24
  • 17
    `basename $filename .exe` would do the same thing. That's assuming you always know what extension you want to remove. – mpe Aug 28 '12 at 14:54
  • 13
    @mpe, you mean `basename "$filename" .exe`. Otherwise filenames with spaces would be bad news. – Charles Duffy Jun 15 '16 at 19:35
  • See also [Extract substring in Bash](https://stackoverflow.com/a/428580/5178726) where also `"${file#prestring}"` is explained. – Aron Hoogeveen May 20 '22 at 15:43

16 Answers16

467

You can also use parameter expansion:

$ filename=foo.txt
$ echo "${filename%.*}"
foo

If you have a filepath and not just a filename, you'll want to use basename first to get just the filename including the extension. Otherwise, if there's a dot only in the path (e.g. path.to/myfile or ./myfile), then it will trim inside the path; even if there isn't a dot in the path, it will get the (e.g. path/to/myfile if the path is path/to/myfile.txt):

$ filepath=path.to/foo.txt
$ echo "${filepath%.*}"
path.to/foo
$ filename=$(basename $filepath)
$ echo $filename
foo.txt
$ echo "${filename%.*}"
foo

Just be aware that if the filename only starts with a dot (e.g. .bashrc) it will remove the whole filename.

ubadub
  • 3,571
  • 21
  • 32
chepner
  • 497,756
  • 71
  • 530
  • 681
  • 12
    here the explanation of the command: https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html – Carlos Robles Jul 06 '16 at 16:33
  • 3
    And here I was about to use `echo -n "This.File.Has.Periods.In.It.txt" | awk -F. '{$NF=""; print $0}' | tr ' ' '.' | rev | cut -c 2- | rev`. Thanks. – user208145 Aug 30 '16 at 23:18
  • 3
    Does this work with files with multiple extensions like `image.png.gz`? – Hawker65 Apr 26 '18 at 08:58
  • 21
    `%.*` will only remove the last extension; if you want to remove *all* the extensions, use `%%.*`. – chepner Apr 26 '18 at 13:20
  • 1
    This seems to work way better than the accepted answer. It only shaves off the last extension if the file has more than one dot, whereas cut removes everything after the first dot. – Dale C. Anderson Aug 28 '18 at 19:08
  • 5
    Be warned this deletes the entire name if there is no extension and the path is relative. E.g., `filename=./ihavenoextension`. – jpmc26 Sep 14 '19 at 09:02
  • 1
    @Hawker65 if you know the file will have a `.png.gz` extension, you can use `{file%.png.gz}`. That will prevent it trimming after periods earlier in the file - or in the path! – mwfearnley Sep 30 '20 at 10:21
  • 1
    This covers all the possibilities: https://stackoverflow.com/a/66177670/12969125 – shaheen g Feb 14 '21 at 02:59
  • @chepner, @mwfearnley, To flexibly handle dot-files, an improvement would be: (1) remove last extension => `echo "$(s=${filename:1}; echo -n ${filename:0:1}; echo ${s%.*})"` ; (2) remove all extensions => `echo "$(s=${filename:1}; echo -n ${filename:0:1}; echo ${s%%.*})"`. – rivy Sep 23 '21 at 20:06
  • This does not work for `tar.gz` or any other extension that has multiple parts with `.`. You would have to use `${file%%.tar*}` – Dave Aug 22 '22 at 14:05
  • bash never did pick up csh's `:r` functionality : `setenv CAB cab.txt; echo $cab:r` and `setenv CAB cab; echo $cab:r` both return `cab` as expected. – ctpenrose Apr 12 '23 at 22:23
187

If you know the extension, you can use basename

$ basename /home/jsmith/base.wiki .wiki
base
Zombo
  • 1
  • 62
  • 391
  • 407
176

You should be using the command substitution syntax $(command) when you want to execute a command in script/command.

So your line would be

name=$(echo "$filename" | cut -f 1 -d '.')

Code explanation:

  1. echo get the value of the variable $filename and send it to standard output
  2. We then grab the output and pipe it to the cut command
  3. The cut will use the . as delimiter (also known as separator) for cutting the string into segments and by -f we select which segment we want to have in output
  4. Then the $() command substitution will get the output and return its value
  5. The returned value will be assigned to the variable named name

Note that this gives the portion of the variable up to the first period .:

$ filename=hello.world
$ echo "$filename" | cut -f 1 -d '.'
hello
$ filename=hello.hello.hello
$ echo "$filename" | cut -f 1 -d '.'
hello
$ filename=hello
$ echo "$filename" | cut -f 1 -d '.'
hello
gniourf_gniourf
  • 44,650
  • 9
  • 93
  • 104
Rohan
  • 52,392
  • 12
  • 90
  • 87
49

If your filename contains a dot (other than the one of the extension) then use this:

echo $filename | rev | cut -f 2- -d '.' | rev
Manish Singh
  • 5,848
  • 4
  • 43
  • 31
  • 1
    I forgot the middle rev, but once I saw it, this was great! – supreme Pooba Sep 29 '16 at 17:11
  • It’s even better with an `-s` option given to `cut`, so that it returns an empty string whenever the filename contains no dot. – Hibou57 Apr 27 '20 at 10:59
  • 4
    This should be the accepted answer in my opinion, since it works on path with dots in them, with hidden files starting with a dot, or even with file with multiple extensions. – Tim Krief Jun 22 '20 at 08:02
  • 2
    What happens with a file like this: `filename=/tmp.d/foo`? – FedKad Sep 13 '20 at 11:17
  • @FedonKadifeli, this works for just the file name, not for full path. But you can get the filename first using a similar approach by using `/` as the delimiter. – Manish Singh Sep 15 '20 at 04:41
  • 2
    It has problems with "dot files" also. Try with `.profile` for example. – FedKad Sep 15 '20 at 12:45
  • @FedonKadifeli use something like this: `basename "$INPUT" | rev | cut -f 2- -d '.' | rev` works perfectly. `$INPUT` is the filename or the path. – donvercety Mar 25 '21 at 11:40
  • This is not a very elegant solution and has real deficiencies, as @FedKad describes. – John Leuenhagen Aug 05 '22 at 18:41
40

Using POSIX's built-in only:

#!/usr/bin/env sh
path=this.path/with.dots/in.path.name/filename.tar.gz

# Get the basedir without external command
# by stripping out shortest trailing match of / followed by anything
dirname=${path%/*}

# Get the basename without external command
# by stripping out longest leading match of anything followed by /
basename=${path##*/}

# Strip uptmost trailing extension only
# by stripping out shortest trailing match of dot followed by anything
oneextless=${basename%.*}; echo "$oneextless" 

# Strip all extensions
# by stripping out longest trailing match of dot followed by anything
noext=${basename%%.*}; echo "$noext"

# Printout demo
printf %s\\n "$path" "$dirname" "$basename" "$oneextless" "$noext"

Printout demo:

this.path/with.dots/in.path.name/filename.tar.gz
this.path/with.dots/in.path.name
filename.tar.gz
filename.tar
filename
Andreas Louv
  • 46,145
  • 13
  • 104
  • 123
Léa Gris
  • 17,497
  • 4
  • 32
  • 41
28
file1=/tmp/main.one.two.sh
t=$(basename "$file1")                        # output is main.one.two.sh
name=$(echo "$file1" | sed -e 's/\.[^.]*$//') # output is /tmp/main.one.two
name=$(echo "$t" | sed -e 's/\.[^.]*$//')     # output is main.one.two

use whichever you want. Here I assume that last . (dot) followed by text is extension.

gniourf_gniourf
  • 44,650
  • 9
  • 93
  • 104
Raghwendra
  • 289
  • 3
  • 3
  • What happens when `file1=/tmp.d/mainonetwosh`? The sed expression should be replaced with `'s/\.[^./]*$//'` – FedKad Sep 13 '20 at 10:23
8
#!/bin/bash
file=/tmp/foo.bar.gz
echo $file ${file%.*}

outputs:

/tmp/foo.bar.gz /tmp/foo.bar

Note that only the last extension is removed.

C. Paul Bond
  • 159
  • 2
  • 3
4

In Zsh:

fullname=bridge.zip
echo ${fullname:r}

It's simple, clean and it can be chained to remove more than one extension:

fullname=bridge.tar.gz
echo ${fullname:r:r}

And it can be combined with other similar modifiers.

beemtee
  • 831
  • 1
  • 8
  • 10
3
#!/bin/bash
filename=program.c
name=$(basename "$filename" .c)
echo "$name"

outputs:

program
gniourf_gniourf
  • 44,650
  • 9
  • 93
  • 104
booboo
  • 110
  • 2
3

My recommendation is to use basename.
It is by default in Ubuntu, visually simple code and deal with majority of cases.

Here are some sub-cases to deal with spaces and multi-dot/sub-extension:

pathfile="../space fld/space -file.tar.gz"
echo ${pathfile//+(*\/|.*)}

It usually get rid of extension from first ., but fail in our .. path

echo **"$(basename "${pathfile%.*}")"**  
space -file.tar     # I believe we needed exatly that

Here is an important note:

I used double quotes inside double quotes to deal with spaces. Single quote will not pass due to texting the $. Bash is unusual and reads "second "first" quotes" due to expansion.

However, you still need to think of .hidden_files

hidden="~/.bashrc"
echo "$(basename "${hidden%.*}")"  # will produce "~" !!!  

not the expected "" outcome. To make it happen use $HOME or /home/user_path/
because again bash is "unusual" and don't expand "~" (search for bash BashPitfalls)

hidden2="$HOME/.bashrc" ;  echo '$(basename "${pathfile%.*}")'
Léa Gris
  • 17,497
  • 4
  • 32
  • 41
Alexey K.
  • 101
  • 4
2

Two problems with your code:

  1. You used a ' (tick) instead of a ` (back tick) to surround the commands that generate the string you want to store in the variable.
  2. You didn't "echo" the variable "$filename" to the pipe into the "cut" command.

I'd change your code to "name=`echo $filename | cut -f 1 -d '.' `", as shown below (again, notice the back ticks surrounding the name variable definition):

$> filename=foo.txt
$> echo $filename
foo.txt
$> name=`echo $filename | cut -f1 -d'.'`
$> echo $name
foo
$> 

EDIT: If I can add to the answer, I'd use the $( ... ) construct as opposed to using back ticks. I think it is a whole lot cleaner, and less prone to tick confusion.

FanDeLaU
  • 318
  • 2
  • 8
  • 2
    This is the only answer that actually tries to answer the question _What's wrong with the following code?_ – kvantour Feb 07 '23 at 12:42
2

Answers provided previously have problems with paths containing dots. Some examples:

/xyz.dir/file.ext
./file.ext
/a.b.c/x.ddd.txt

I prefer to use |sed -e 's/\.[^./]*$//'. For example:

$ echo "/xyz.dir/file.ext" | sed -e 's/\.[^./]*$//'
/xyz.dir/file
$ echo "./file.ext" | sed -e 's/\.[^./]*$//'
./file
$ echo "/a.b.c/x.ddd.txt" | sed -e 's/\.[^./]*$//'
/a.b.c/x.ddd

Note: If you want to remove multiple extensions (as in the last example), use |sed -e 's/\.[^/]*$//':

$ echo "/a.b.c/x.ddd.txt" | sed -e 's/\.[^/]*$//'
/a.b.c/x

However, this method will fail in "dot-files" with no extension:

$ echo "/a.b.c/.profile" | sed -e 's/\.[^./]*$//'
/a.b.c/

To cover also such cases, you can use:

$ echo "/a.b.c/.profile" | sed -re 's/(^.*[^/])\.[^./]*$/\1/'
/a.b.c/.profile
FedKad
  • 493
  • 4
  • 19
2

This one covers all possibilities! (dot in the path or not; with extension or no extension):

tmp1=${filename##*/};tmp2=${tmp1:1};filename_noextension=$(echo -n ${tmp1:0:1};echo ${tmp2%.*});echo $filename_noextension

Notes:

  • It gives you the filename without any extension. So there is no path in the $filename_noextension variable.
  • You end up with two unwanted variables $tmp1 and $tmp2. Make sure you are not using them in your script.

examples to test:

filename=.bashrc; echo "filename: $filename"; tmp1=${filename##*/};tmp2=${tmp1:1};filename_noextension=$(echo -n ${tmp1:0:1};echo ${tmp2%.*}); echo "filename without extension: $filename_noextension"

filename=.bashrc.txt; echo "filename: $filename"; tmp1=${filename##*/};tmp2=${tmp1:1};filename_noextension=$(echo -n ${tmp1:0:1};echo ${tmp2%.*}); echo "filename without extension: $filename_noextension"

filename=.bashrc.txt.tar; echo "filename: $filename"; tmp1=${filename##*/};tmp2=${tmp1:1};filename_noextension=$(echo -n ${tmp1:0:1};echo ${tmp2%.*}); echo "filename without extension: $filename_noextension"

filename=~/.bashrc; echo "filename: $filename"; tmp1=${filename##*/};tmp2=${tmp1:1};filename_noextension=$(echo -n ${tmp1:0:1};echo ${tmp2%.*}); echo "filename without extension: $filename_noextension"

filename=~/.bashrc.txt.tar; echo "filename: $filename"; tmp1=${filename##*/};tmp2=${tmp1:1};filename_noextension=$(echo -n ${tmp1:0:1};echo ${tmp2%.*}); echo "filename without extension: $filename_noextension"

filename=bashrc; echo "filename: $filename"; tmp1=${filename##*/};tmp2=${tmp1:1};filename_noextension=$(echo -n ${tmp1:0:1};echo ${tmp2%.*}); echo "filename without extension: $filename_noextension"

filename=bashrc.txt; echo "filename: $filename"; tmp1=${filename##*/};tmp2=${tmp1:1};filename_noextension=$(echo -n ${tmp1:0:1};echo ${tmp2%.*}); echo "filename without extension: $filename_noextension"

filename=bashrc.txt.tar; echo "filename: $filename"; tmp1=${filename##*/};tmp2=${tmp1:1};filename_noextension=$(echo -n ${tmp1:0:1};echo ${tmp2%.*}); echo "filename without extension: $filename_noextension"

filename=~/bashrc; echo "filename: $filename"; tmp1=${filename##*/};tmp2=${tmp1:1};filename_noextension=$(echo -n ${tmp1:0:1};echo ${tmp2%.*}); echo "filename without extension: $filename_noextension"

filename=~/bashrc.txt.tar; echo "filename: $filename"; tmp1=${filename##*/};tmp2=${tmp1:1};filename_noextension=$(echo -n ${tmp1:0:1};echo ${tmp2%.*}); echo "filename without extension: $filename_noextension"

shaheen g
  • 691
  • 6
  • 6
1

As pointed out by Hawker65 in the comment of chepner answer, the most voted solution does neither take care of multiple extensions (such as filename.tar.gz), nor of dots in the rest of the path (such as this.path/with.dots/in.path.name). A possible solution is:

a=this.path/with.dots/in.path.name/filename.tar.gz
echo $(dirname $a)/$(basename $a | cut -d. -f1)
MadMage
  • 186
  • 1
  • 7
  • This one strips "tar.gz" by selecting characters before the first instance of a dot in the filename not counting the path. One probably doesn't want to strip extensions that way. – Frotz Oct 24 '18 at 08:30
  • If you know it ends in `.tar.gz`, you can just use `$(basename "$a" .tar.gz)`. Also, make sure to wrap your variable in quotes everywhere if there's any chance it will contain spaces or other weird characters! – mwfearnley Sep 30 '20 at 10:26
0

After trying several solutions that didn't work for dot files, here is my Bash compatible unelegant solution.

# Given a file path, return only the file name, stripped of its extension.
basefilename()
{
    filename="$(basename "$1")"
    prefix=

    if [[ ${filename::1} == . ]]; then
        prefix=.
        filename="${filename:1}"
    fi

    echo -n "$prefix"
    echo "$filename" | rev | cut -f 2- -d '.' | rev
}

I tested it only on a few cases though. Let me know if you have some improvements.

foxesque
  • 590
  • 6
  • 12
-2

enter image description here

Assuming your files have .new extension

ls -1 | awk '{ print "mv "$1" `basename "$1" .new`"}' | sh

Since it is not showing special quotes after posting, please see image.

JoSSte
  • 2,953
  • 6
  • 34
  • 54