wiltonsr
wiltonsr

Reputation: 1027

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

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.

Upvotes: 5

Views: 1775

Answers (4)

wiltonsr
wiltonsr

Reputation: 1027

For registration only, thanks to @Andy Lester's comment I also found a simple way to solve the problem with grep and cut, without the need for regex:

grep -a -m1 'KEY1' file | cut -d "\"" -f2

return

VALUE1

Upvotes: 2

dawg
dawg

Reputation: 103874

You can also use sed:

sed -nE 's/^KEY1="(.*)"/\1/p;q' file

The p;q means 'print' then 'quit'

Upvotes: 2

anubhava
anubhava

Reputation: 785246

You can exit after printing first match:

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

VALUE1

Upvotes: 3

Timur Shtatland
Timur Shtatland

Reputation: 12347

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.

Upvotes: 7

Related Questions