Reputation: 225
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)
Upvotes: 0
Views: 214
Reputation: 241908
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.
Upvotes: 3
Reputation: 2621
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)
Upvotes: 1
Reputation: 91430
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"
Upvotes: 0