1

I have a line of text which looks like hh^ay-pau+h@ow, I want to extract the text between - and + which in this case is pau. This should be done in bash. Any help would be appreciated. EDIT: I want to extract the text between the first occurence of the tokens PS: My google search didn't take me anywhere. I apologize if this question is already asked.

tster
  • 17,883
  • 5
  • 53
  • 72
dineshdileep
  • 715
  • 2
  • 13
  • 24

6 Answers6

5

The way to do this in pure bash, is by using parameter expansions in bash

$ a=hh^ay-pau+h@ow
$ b=${a%%+*}
$ c=${b#*-}
$ echo $c
pau

b: remove everything including and behind the first + occurence c: remove everything excluding and before the first - ocurrence

More info about substring removing in bash parameter expansion

Bernhard
  • 3,619
  • 1
  • 25
  • 50
2

Try

grep -Po "(?<=\-).*?(?=\+)"

For example,

echo "hh^ay-pau+h@ow" | grep -Po "(?<=\-).*?(?=\+)"
Vytenis Bivainis
  • 2,308
  • 21
  • 28
2

If you have only one occurence of - and + you can use cut:

 $ echo "hh^ay-pau+h@ow" | cut -d "-" -f 2 | cut -d "+" -f 1
 pau
2

Assuming one occurence of + and -, you can stick to bash

IFS=+- read -r _ x _ <<<'hh^ay-pau+h@ow'             
echo $x
pau
iruvar
  • 22,736
  • 7
  • 53
  • 82
0

If you're guarenteed to only have one - and one + .

 % echo "hh^ay-pau+h@ow" | sed -e 's/.*-//' -e 's/+.*//'
 pau
eduffy
  • 39,140
  • 13
  • 95
  • 92
  • could you please explain the sed command, actually I wanted to extract the text between the first occurence of "-" and "+". There are multiple occurences of both tokens – dineshdileep May 26 '14 at 17:52
0
echo "hh^ay-pau+h@ow" | awk -F'-' '{print $2}' |awk -F'+' '{print $1}'
Emilio Galarraga
  • 659
  • 1
  • 8
  • 14