With grep
, you can use a question mark ?
to signify an optional character, that is a character that is to be matches 0 or 1 times.
$ foo=qwerasdf
$ grep -Eo fx? <<< $foo
f
The question is does Bash String Manipulation have a similar feature? Something like
$ echo ${foo%fx?}
Continuing Lines You can do this in two ways: by ending a line with a backslash, or by not closing a quote mark (i.e., by including RETURN in a quoted string).
You can use a bash parameter expansion, sed, cut and tr to trim a string. Output: Helloworld. "${foo// /}" removes all space characters, "$foo/ /" removes the first space character.
To initialize a string, you directly start with the name of the variable followed by the assignment operator(=) and the actual value of the string enclosed in single or double quotes. Output: This simple example initializes a string and prints the value using the “$” operator.
You're probably talking about parameter expansion. It uses shell patterns, not regular expression, so the answer is no.
Upon further reading, I noticed that if you
shopt -s extglob
you can use extended pattern matching which can achieve something similar to regex, albeit with slightly different syntax.
Check this out:
word="mre"
# this returns true
if [[ $word == m?(o)re ]]; then echo true; else echo false; fi
word="more"
# this also returns true
if [[ $word == m?(o)re ]]; then echo true; else echo false; fi
word="mooooooooooore"
# again, true
if [[ $word == m+(o)re ]]; then echo true; else echo false; fi
Works with parameter expansion too,
word="noooooooooooo"
# outputs 'nay'
echo ${word/+(o)/ay}
# outputs 'nayooooooooooo'
echo ${word/o/ay}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With