How to remove the extension of a file?

bash, cygwin, linux, unix

Solution

To remove a string from the end of a BASH variable, use the `${var%ending}` syntax. It's one of a number of string manipulations available to you in BASH.

Use it like this:

# Run in the same directory as the files
for FILENAME in *.bak; do mv "$FILENAME" "${FILENAME%.bak}"; done

That works nicely as a one-liner, but you could also wrap it as a script to work in an arbitrary directory:

# If we're passed a parameter, cd into that directory. Otherwise, do nothing.
if [ -n "$1" ]; then
  cd "$1"
fi
for FILENAME in *.bak; do mv "$FILENAME" "${FILENAME%.bak}"; done

Note that while quoting your variables is almost always a good practice, the `for FILENAME in *.bak` is still dangerous if any of your filenames might contain spaces. Read David W.'s answer for a more-robust solution, and this document for alternative solutions.

Problem

I have a folder that is full of .bak files and some other files also. I need to remove the extension of all .bak files in that folder. How do I make a command which will accept a folder name and then remove the extension of all .bak files in that folder ? Thanks.

Original source