Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get my Perl one-liner to show only the first regex match in the file?

Tags:

regex

perl

I have a file with this format:

KEY1="VALUE1"
KEY2="VALUE2"
KEY1="VALUE2"

I need a perl command to only get first occurrence of KEY1, ie VALUE1.

I'm using this command:

perl -ne 'print "$1" if /KEY1="(.*?)"/' myfile

But the result is:

VALUE1VALUE2

EDIT

The solution must be with perl command, because the system there is no other regex tool.

like image 334
wiltonsr Avatar asked Dec 18 '22 11:12

wiltonsr


2 Answers

Add and last to your one-liner like so (extra quotes removed):

perl -ne 'print $1 and last if /KEY1="(.*?)"/' myfile

This works because -n switch effectively wraps your code in a while loop. Thus, if the pattern matches, print is executed, which succeeds and thus causes last to be executed. This exits the while loop.

You can also use the more verbose last LINE, which specifies the (implicit) label of the while loop that iterates over the input lines. This last form is useful for more complex code than you have here, such as the code involving nested loops.

like image 145
Timur Shtatland Avatar answered Jan 05 '23 00:01

Timur Shtatland


You can exit after printing first match:

perl -ne '/KEY1="([^"]*)"/ && print ($1 . "\n") && exit' file

VALUE1
like image 36
anubhava Avatar answered Jan 05 '23 00:01

anubhava