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.
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.
You can exit after printing first match:
perl -ne '/KEY1="([^"]*)"/ && print ($1 . "\n") && exit' file
VALUE1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With