Trim variable in bash

Viewed 125

I need to trim the variable wordpress.tar.gz to wordpress.

I've tried:

#!/bin/bash
dir=wordpress.tar.gz
echo $dir
RELEASE=$($dir | sed "s/-.tar.gz//")
echo ${RELEASE}
2 Answers

You may use string expansion:

RELEASE="${dir%%.*}"

See the online Bash demo:

dir=wordpress.tar.gz
RELEASE="${dir%%.*}"
echo "$RELEASE"
# => wordpress

The ${dir%%.*} part removes the longest chunk of text from the end (due to %%) until the first dot char.

If you want to use sed, you may remove all the string starting with (and including) the first dot:

RELEASE="$(sed 's/\..*//' <<< $dir)"

Here, \..* matches a dot and then any zero or more chars to the end of string, and the match is replaced with an empty string (is removed) since the RHS is empty.

RELEASE=$(echo $dir | sed "s/\.tar\.gz//")
Related