Search code examples
bashsubstitutionfile-extension

How to remove all file extensions in bash?


x=./gandalf.tar.gz
noext=${x%.*}
echo $noext

This prints ./gandalf.tar, but I need just ./gandalf. I might have even files like ./gandalf.tar.a.b.c which have many more extensions.

I just need the part before the first .


Solution

  • If you want to give sed a chance then:

    x='./gandalf.tar.a.b.c'
    sed -E 's~(.)\..*~\1~g' <<< "$x"
    
    ./gandalf
    

    Or 2 step process in bash:

    x="${s#./}"
    echo "./${x%%.*}"
    
    ./gandalf