1

I tried to figure out how to replace a string variable to '*'

a="bamtools/*/*bam_metric.summary.tsv"
## not working    
echo ${a/*\*/}

I would like to see bam_metric.summary.tsv after substitution.

2
  • 2
    Quotes are something to remove when you need to, not something to add when you need to. Given that mindset your starting point should have been echo "${a/*\*/}" unless you needed to remove the quotes. See mywiki.wooledge.org/Quotes. Commented Sep 5 at 18:54
  • Another approach: [[ "$a" =~ [^*]*$ ]] && echo "${BASH_REMATCH[0]}" Commented Sep 5 at 21:11

1 Answer 1

4

Try:

$ echo "${a/*[*]/}"
bam_metric.summary.tsv

Other parameter substitution ideas:

$ echo "${a##*\*}"
bam_metric.summary.tsv

$ echo "${a##*[*]}"
bam_metric.summary.tsv
Sign up to request clarification or add additional context in comments.

4 Comments

Using a character class like that to quote individual special characters in shell patterns and regexes is one of may favorite tricks. I find it much easier to read than using backslashes, especially when multiple levels of quoting would require backslashes themselves to be escaped.
@JohnBollinger nit-pick: [*] is a bracket expression, not a character class :-). [:space:] is a character class while [[:space:]] is a bracket expression containing a character class. That's POSIX terminology, I know there's other terminology out there (perl? PCRE? idk..) that refers to just about EVERYTHING (e.g. all 3 of [:space:], [[:space:]], and \s) as a character class but that terminology is clear as mud and so IMO best avoided.
I acknowledge that you are describing the terminology used by POSIX for POSIX regular expressions, and partially by the Bash manual in conjunction with pathname expansion. Consistency with that terminology would have been appropriate in the present context; mea culpa. However, as you observe, usage of the term "character class" to describe bracket expressions is standard in other contexts, and few of us work exclusively in just one, so I think terminology purism is probably a lost cause here.
@JohnBollinger I'm just thinking of beginners - back in the day it took me longer than it should have to wrap my head around this part of regexps, in large part due to the nebulous use of the term "character class" in texts. I do agree it's probably a lost cause though, unfortunately.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.