简体   繁体   中英

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.

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 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\.\K\d\.\d\.\d'

The grep command has the -m N option that will make grep stop after the first N matches.

In general, the way to only get the first line of output in unix is to send the output to the head command. To get just the first line of output, do:

grep -Po '(?<=.so.)\d.\d.\d' | head -n 1

That "1" can be any number.

Use

awk -F'[.]so[.]' '/^libpackage-/{sub(/,$/,"", $NF);print $NF; exit}'

Split with .so. separator, find the line beginning with libpackage- , remove a comma from the end of the last field, print it and stop processing.

Another way:

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

-m1 gets the first instance. I updated the expression: literal periods should be escaped, and \d+ will match one or more digits.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM