0

I searched a lot but I didnt find answers which would suit what I am looking for so I am posting this question.

I want to extract the first occurance of 'par','comp' 'order' and 'nameprefix'. How to do this for the example input? Is there any perl oneliners to do it?

    wertydhhdbc->auCdl = '( nil
    par    (xyz)
    comp     asd1
    order        (done)
    namePrefix        "X"
    par    (xyz)
    comp     asd
    order        (done)
    namePrefix        "R"
    namePrefix        "X"
    par    (qwer)
    comp     key
    order        (done)
    namePrefix        "X"
    comp     key
    order        (done )
    par    (qwer)
    order        (done)
Daniel Daranas
  • 22,454
  • 9
  • 63
  • 116
unkaitha
  • 225
  • 1
  • 5
  • 13

3 Answers3

3

Yes, you can use a simple Perl onle-liner to show the first line containing e.g. par:

perl -ne 'if (/par/) { print; last; }'  1.txt

The -n switch makes perl go over the input file line by one. The code then makes it print the line and stop once the given pattern is found.

Update:

To search for the first occurence of each of the words, a different technique must be used:

perl -ne 'if(/(comp|par|order)/) {$f{$1}++; print if 1 == $f{$1} ; last if 3 == keys %f}' 1.txt

3 is the number of words you are searching for.

choroba
  • 231,213
  • 25
  • 204
  • 289
  • Can i accomadate all the strings i want to extract in the same oneliner?????? for eg.: if (/par && comp && order/) or anything similar way??? – unkaitha Sep 10 '12 at 07:41
1

Assume you want the whole line of the first occurance of 'par','comp' 'order' and 'nameprefix'. Use \b to avoid matching words like orders

print $1 if $str =~ /(\b(?:par|comp|order|nameprefix)\b.+)/

This would output

par    (xyz)
chifung7
  • 2,531
  • 1
  • 19
  • 17
0

How about:

my ($par, $comp, $order, $nameprefix) = ($str =~ /par\s+(.+?)\s+comp\s+(.+?)\s+order\s+(.+?)\s+namePrefix\s+(.+?)\s/s);
print "par=$par\ncomp=$comp\norder=$order\nnameprefix=$nameprefix\n";

output:

par=(xyz)
comp=asd1
order=(done)
nameprefix="X"
Toto
  • 89,455
  • 62
  • 89
  • 125