3

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}
Ryszard Czech
  • 18,032
  • 4
  • 24
  • 37
NasKar
  • 59
  • 5
  • You have an issue with the regex pattern: dots must be escaped and the dash should not have been used, I do not see any dash in the variable. – Ryszard Czech Sep 19 '20 at 21:10

2 Answers2

2

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.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
1
RELEASE=$(echo $dir | sed "s/\.tar\.gz//")
Michael
  • 5,095
  • 2
  • 13
  • 35
  • It does not make sense to fork two sub-shells (one for `$(cmds)`, another for `| cmd`) and spawn `sed` to do exactly what the standard POSIX's built-in variable expansion can do: `RELEASE="${dir%.tar.gz}"` – Léa Gris Sep 19 '20 at 17:59