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

sed: Extract version number from string

Input: adcheck (CentrifyDC 4.4.3-421)

Desired output: 4.4.3

What I thought would work:

/usr/share/centrifydc/bin/adcheck --version | sed -n '/Centrify DC /,/-/p'

But that outputs nothing??

Thank you!

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Your solution does not work because you are trying to use addresses to select a piece of a line, but addresses just select a bunch of lines. Your code /Centrify DC /,/-/p would print all lines between one line which contains Centrify DC and another line which contains -. It does not work inside one line only, however

What you want is to remove everything from the line, except the version number. I would recommend you to group the version number and replace all the content of the line by it:

$ echo "adcheck (CentrifyDC 4.4.3-421)" | sed 's/^.*[^0-9]([0-9]*.[0-9]*.[0-9]*).*$/1/'
4.4.3

Here we put the version number in a group with ([0-9]*.[0-9]*.[0-9]*) and replace all the line by the group (referenced by 1).

If your input has more than one line, it may need some tunneling:

$ cat file
adcheck (CentrifyDC 4.4.3-421)
another line
still another line
$ sed 's/^.*[^0-9]([0-9]*.[0-9]*.[0-9]*).*$/1/' file
4.4.3
another line
still another line

In this case, pass the -n flag to sed for inhibiting the default printing. Then, give an address to the s/// command (such as /adcheck (CentrifyDC /) for guaranteeing that the replacement will occur only in the line which matchs the address. Finally add the p flag to the s/// command - it will print the line just after the replacement:

$  sed -n '/adcheck (CentrifyDC /s/^.*[^0-9]([0-9]*.[0-9]*.[0-9]*).*$/1/p' file
4.4.3

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

...