2

How do you use regular expression in bash to search any given string and remove occurrence of particular word? This is the expression I've come up with

^([A-Za-z-]+)(-).*(el6.*)$

What I would like to accomplish is, in a given string like cjkuni-ukai-fonts-0.2.20080216.1-35.el6.noarch, the expression should remove cjkuni-ukai-fonts- and el6.noarch, and leave only 0.2.20080216.1-35. As I'm very limited in what I can install on the system, I cannot use perl or other non basic commands. Any help would be appreciated.

P.S : I've tried sed, but I couldn't get it work.

3
  • What system are you running? Do you have access to GNU tools? Does your version of bash even support regular expressions?
    – terdon
    Nov 11, 2014 at 3:54
  • I'm running CentOS and it does support regular expression. Nov 11, 2014 at 4:04
  • And perl is not installed? Really?
    – terdon
    Nov 11, 2014 at 4:15

1 Answer 1

5

If you really must do it in pure bash:

$ foo="cjkuni-ukai-fonts-0.2.20080216.1-35.el6.noarch"
$ [[ $foo =~ [0-9.]+-[0-9]* ]] && echo $BASH_REMATCH
0.2.20080216.1-35

If you're OK with a sed solution:

$ sed 's/.*-\([0-9.]*-[0-9]*\).*/\1/' <<<$foo
0.2.20080216.1-35

If you have access to GNU grep, you could also do:

$ grep -oE -- '[0-9.]+-[0-9]*' <<<$foo
0.2.20080216.1-35

or

$ grep -oP -- '[.\d]+-\d+' <<<$foo
0.2.20080216.1-35

Finally, since you're running a CentOS system, it is a fairly safe bet that Perl is installed, so you could also do:

$ perl -pe 's/.*?([0-9.]+-[0-9]*).*/$1/' <<<$foo
0.2.20080216.1-35
2
  • Depending on what the OP means by "I cannot use Perl", PCRE support for grep may not be available. This shouldn't be the case on a standard CentOS install, though...
    – Joseph R.
    Nov 11, 2014 at 4:12
  • @JosephR. I know, that's why I clarified that it needs GNU grep. You need that for -o anyway, let alone the PCREs. No idea what makes the OP thing that perl itself is not installed by default on CentOS. Perhaps it's an extremely minimalist setup.
    – terdon
    Nov 11, 2014 at 4:14

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .