0

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?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Sabo Boz
  • 1,683
  • 4
  • 13
  • 29
  • 1
    These expansion substitutions don't use regular expressions, they use wildcard (or "glob") patterns, which are [just similar enough to be confusing](https://stackoverflow.com/questions/23702202/what-are-the-differences-between-glob-style-pattern-and-regular-expression) – Gordon Davisson Jan 30 '22 at 19:46
  • Why did you delete your previous post? https://stackoverflow.com/questions/70917837/using-and-in-bash-regex-and-replacing-spaces-empty-strings – Léa Gris Jan 30 '22 at 20:36
  • @LéaGris I just thought this question worded my issue a bit more clearly – Sabo Boz Jan 30 '22 at 21:23

3 Answers3

2

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
Fravadona
  • 13,917
  • 1
  • 23
  • 35
2

I would remove the hyphens first:

a='and/or fox-----'
a=${a//-/}
echo $a
a=${a//[\/\_ ]/-}
echo $a

This yields and-or-fox.

Katharine Osborne
  • 6,571
  • 6
  • 32
  • 61
1

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"

Léa Gris
  • 17,497
  • 4
  • 32
  • 41
  • 1
    sorry what does the part after the =~ on the 6th line do? – Sabo Boz Jan 30 '22 at 21:20
  • 2
    @SaboBoz `=~` is the way to use **regex** in bash, while what you use in your code is called **glob**. The regex here means: capture everything up to the last _non-dash_ character – Fravadona Jan 30 '22 at 21:42