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.
Asked
Active
Viewed 1.1k times
1
tster
- 17,334
- 5
- 50
- 70
dineshdileep
- 625
- 2
- 10
- 23
6 Answers
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,499
- 1
- 24
- 50
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
Nicolae Namolovan
- 101
- 2
2
Assuming one occurence of + and -, you can stick to bash
IFS=+- read -r _ x _ <<<'hh^ay-pau+h@ow'
echo $x
pau
iruvar
- 21,786
- 6
- 51
- 81
1
Try
grep -Po "(?<=\-).*?(?=\+)"
For example,
echo "hh^ay-pau+h@ow" | grep -Po "(?<=\-).*?(?=\+)"
Vytenis Bivainis
- 2,208
- 18
- 25
0
If you're guarenteed to only have one - and one + .
% echo "hh^ay-pau+h@ow" | sed -e 's/.*-//' -e 's/+.*//'
pau
eduffy
- 37,790
- 12
- 92
- 91
-
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
- 555
- 1
- 7
- 13