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
178 views
in Technique[技术] by (71.8m points)

linux - Get only one instance of a regex instead of multiple

I have a text file that contains:

libpackage-example1.so.3.2.1,
libpackage-example2.so.3.2.1,
libpackage-example3.so.3.2.1,
libpackage-example4.so.3.2.1

I only want to get one instance of "3.2.1", but when I run the command below:

grep -Po '(?<=.so.)d.d.d'

The result is

3.2.1
3.2.1
3.2.1
3.2.1

instead of just one "3.2.1". I think making it a lazy regex would work, but I do not know how to do that.

question from:https://stackoverflow.com/questions/65946432/get-only-one-instance-of-a-regex-instead-of-multiple

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

1 Answer

0 votes
by (71.8m points)

The regex is applied to each line. No matter how you change the regex, if the the whole file contains multiple matching lines then all of them will be printed.

However, you can limit the number of matched lines using the -m option. -o -m 1 will output at most all matches from one line before exiting. If there are multiple matches in one line use grep ... | head -n1 instead.

Also, keep in mind that . means any character. To specify a literal dot use . or [.].

Perl regexes also support K which makes writing easier. Only the part after the last K will be printed.

grep -Pom1 '.so.Kd.d.d'

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

2.1m questions

2.1m answers

60 comments

57.0k users

...