Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
160 views
in Technique[技术] by (71.8m points)

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.

question from:https://stackoverflow.com/questions/65829505/how-can-i-get-my-perl-one-liner-to-show-only-the-first-regex-match-in-the-file

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...