String processing, optional character

With grep can you use a question mark ? to indicate an optional character, which is a character that must match 0 or 1 time.

 $ foo=qwerasdf $ grep -Eo fx? <<< $foo f 

The question is, does Bash String Manipulation have a similar function? Sort of

 $ echo ${foo%fx?} 
+4
source share
1 answer

You are probably talking about parameter expansion . It uses shell patterns, not regex, so the answer is no .

After further reading, I noticed that if you

 shopt -s extglob 

you can use advanced pattern matching , which can achieve something that looks like a regular expression, albeit with a slightly different syntax.

Check this:

 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 

Also works with parameter extension,

 word="noooooooooooo" # outputs 'nay' echo ${word/+(o)/ay} # outputs 'nayooooooooooo' echo ${word/o/ay} 
+5
source

Source: https://habr.com/ru/post/1440743/


All Articles