How to Replace file Extension in Bash using `basename`

The aim of this pageđź“ť is to explain extension replacement in shell scripting based on the particular example of replacing a file extension with .sh.

Pavol Kutaj
1 min readApr 16, 2024
  • To replace an extension in a file, you can use parameter expansion in shell scripting.
  • The correct syntax to replace an extension is ${markdown_file//.md/.sh}, where .md is replaced with .sh.
  • Another approach is to use the basename command to extract the file without the path and extension.
  • You can concatenate the new extension to the extracted file to replace the extension.
  • The basename command is used to strip the directory and suffixes from files.
  • To remove a specific extension using basename, you need to specify the extension value you want to remove. basename "${markdown_file}" .md removes the .md extension from the variable which can be a full absolute path to the file.
function msh {
local markdown_file="$1"
if [[ "${markdown_file: -2}" != "md" ]]; then
echo "~~> ${markdown_file} is not a markdown file"
return 1
fi
shell_file="$(basename "$markdown_file" .md).sh"
touch "$shell_file"
echo "~~> ${shell_file} created"
}
  • As for the tests, the correct way to extract the last 2 characters of a string is ${markdown_file: -2} using negative indices in parameter expansion.
  • Note the danger of using ${markdown_file:-2} . There, a hyphen - is for parameter expansion with a default value, not for extracting the last characters.

LINKS

https://www.gnu.org/software/coreutils/manual/html_node/basename-invocation.html#basename-invocation

--

--

Pavol Kutaj

Today I Learnt | Infrastructure Support Engineer at snowplow.io with a passion for cloud infrastructure/terraform/python/docs. More at https://pavol.kutaj.com