Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String manipulation, optional character

Tags:

bash

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?}
like image 241
Zombo Avatar asked Oct 19 '12 09:10

Zombo


People also ask

When you want a string to have multiple lines which special character is preceded and follow the string value?

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).

How do I shorten a string in bash?

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.

How do you declare a string in bash?

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.


1 Answers

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}
like image 53
doubleDown Avatar answered Oct 29 '22 18:10

doubleDown