In bash I have the following code:
a='and/or fox-----'
a=${a//[\/\_ ]/-}
a=${a//- $/ }
echo $a
With the 3rd line I want to replace the trailing '-' with an empty string, and I know in some contexts the $
means "one or more at the end of the string". However, the result I'm getting is and-or-fox-----
. Does anyone know how to get a
to be and-or-fox
?
CodePudding user response:
I would remove the hyphens first:
a='and/or fox-----'
a=${a//-/}
echo $a
a=${a//[\/\_ ]/-}
echo $a
This yields and-or-fox
.
CodePudding user response:
You can enable bash extended globbing (if not already enabled) and use it with a shell parameter expansion
#!/bin/bash
shopt -s extglob
a='and-or-fox-----'
echo "${a%%*(-)}"
output:
and-or-fox
CodePudding user response:
Replace with Bash's replace variable expansion and extract with Bash Regex all within same statement:
#!/usr/bin/env bash
a='and/or fox-----'
# Extracting with bash regex
[[ ${a//[\/\_]/-} =~ (.*[^-]) ]] || :
a=${BASH_REMATCH[1]}
printf %s\\n "$a"