1

Here is the text:

this is text this is text this is text this is text pattern_abc"00a"this is text this is text this is text this is textthis is text this is text pattern_def"001b"this is text this is text

in the output, I would like:

00a
001b

note: The values I look for are of random length and contents

I use 2 expressions:

exp_1 = grep -oP "(?<=pattern_abc\")[^\"]*"
exp_2 = grep -oP "(?<=pattern_def\")[^\"]*"

egrep does not work (I got "egrep: egrep can only use the egrep pattern syntax")

I try:

cat test | exp_1 && exp_2 
cat test | (exp_1 && exp_2) 
cat test | exp_1 | exp_2
cat test | (exp_1 | exp_2)

and lastly:

grep -oP "((?<=pattern_abc\")[^\"]* \| (?<=pattern_def\")[^\"]*)" test 
 grep -oP "((?<=pattern_abc\")[^\"]* | (?<=pattern_def\")[^\"]*)" test 

Any idea? thank you very much !

0

3 Answers 3

2

You can use this grep,

grep -oP "(?<=pattern_(abc|def)\")[^\"]*" file
1

You can use awk like this:

awk -F\" '{for (i=2;i<NF;i+=2) print $i}' file
00a
001b

If the pattern_* is important you can use this gnu awk (due to RS)

awk -v RS="pattern_(abc|def)" -F\" 'NR>1{print $2}'
00a
001b
0

And another method through grep with Perl-regex option,

$ grep -oP '\"\K[^\"]*(?="this)' file
00a
001b

It works only if the string you want to match is followed by "this.

OR

You could use the below command which combines the two search patterns,

$ grep -oP 'pattern_abc"\K[^"]*|pattern_def"\K[^"]*' file
00a
001b
1
  • Thanks again Avinash; your tip is very interesting indeed; but is there any way to filter with _abc & _def
    – blue_xylo
    Commented Jun 16, 2014 at 12:39

Not the answer you're looking for? Browse other questions tagged or ask your own question.