user788171
user788171

Reputation: 17553

bash, extract string between two patterns

I have a text file that contains a snippet like this:

[#0] PROGRESS:Eval -- P values for  mu_sig-130-0 =  1
        CLs      = 0.0463722 +/- 0
        CLb      = 0.499991 +/- 0
        CLsplusb = 0.0231857 +/- 0

I would like to find the CLs line, and then print out just the number 0.0463722

Is there a way to do this via bash command line?

EDIT: the numbers can change from file to file, but the rest of that line stays the same.

Upvotes: 3

Views: 2291

Answers (6)

Zombo
Zombo

Reputation: 1

awk '$1 == "CLs", $0 = $3'

Result

0.0463722

Upvotes: 2

Endoro
Endoro

Reputation: 37589

GNU sed

sed '/CLs\s/!d;s/.*=\s\([.0-9]\+\).*/\1/' file

Upvotes: 0

jaypal singh
jaypal singh

Reputation: 77185

Using sed

sed -nr '/\bCLs\b/ {s/.*= ([0-9.]+) .*/\1/p}' inputFile

Upvotes: 2

Kent
Kent

Reputation: 195289

this grep line would work no matter how the other lines look like. (you mentioned that line is unique).

grep -oP "^\s*CLs\s*=\s*\K[0-9.]*" file

Upvotes: 0

iruvar
iruvar

Reputation: 23404

awk is probably the way to go, as in the other answers. Here's a GNU grep alternative, with PCRE regex enabled

echo '    CLs      = 0.0463722 +/- 0' | grep -Po 'CLs\s+=\s+\K\d[.]\d+(?=[^\d])'
0.0463722

Upvotes: 0

hek2mgl
hek2mgl

Reputation: 158280

You can use awk for this:

awk '/    CLs      = 0.0463722 \+\/\- 0/ {print $3}' yourfile

Or if you just looking for the line that contains CLs= (likely) then generalize the pattern to:

awk '/ CLs[ ]*=/ {print $3}' yourfile

Upvotes: 1

Related Questions