Home > Net >  Store grep within variable and do a sed in bash
Store grep within variable and do a sed in bash

Time:11-22

I have a file with multiple content such as :

Create initial parsimony tree by phylogenetic likelihood library (PLL)... 0.022 seconds
Perform fast likelihood tree search using LG I G model...
Estimate model parameters (epsilon = 5.000)
Perform nearest neighbor interchange...
Estimate model parameters (epsilon = 1.000)
1. Initial log-likelihood: -30833.549
Optimal log-likelihood: -30833.420
Proportion of invariable sites: 0.016
Gamma shape alpha: 2.035
Parameters optimization took 1 rounds (0.226 sec)
Time for fast ML tree search: 2.912 seconds
NOTE: ModelFinder requires 64 MB RAM!
ModelFinder will test up to 546 protein models (sample size: 1544) ...
 No. Model         -LnL         df  AIC          AICc         BIC
  1  LG            31317.712    31  62697.424    62698.736    62863.030
  2  LG I          31170.012    32  62404.024    62405.422    62574.972
  3  LG G4         30870.402    32  61804.803    61806.201    61975.751
  4  LG I G4       30833.404    33  61732.808    61734.294    61909.098
  5  LG R2         30881.301    33  61828.602    61830.088    62004.892
  6  LG R3         30831.187    35  61732.374    61734.045    61919.349
Akaike Information Criterion:           VT F R4
Corrected Akaike Information Criterion: VT F R4
Bayesian Information Criterion:         VT F R4
Best-fit model: VT F R4 chosen according to BIC
other content....

And I would like to store using bash command the element after the part :

Bayesian Information Criterion:

within a variable called : The_variable.

So far I tried :

The_variable="$(grep 'Bayesian Information Criterion:' the_file.txt)"

which gives me all the grep line

echo $The_variable
Bayesian Information Criterion: VT F R4

but I would like it to store only the VT F R4 part.

To isolate that part I tried :

sed 's@.*: @@g' $VAR

Any idea ?

CodePudding user response:

It is easier in awk:

awk -F ' *: *' '$1 == "Bayesian Information Criterion" {print $2}' file

VT F R4

# to save this in a variable:
myvar=$(awk -F ' *: *' '$1 == "Bayesian Information Criterion" {print $2}' file)

This gnu-grep solution would also work with \K:

grep -oP 'Bayesian Information Criterion:\h*\K. ' file

VT F R4

Or this sed:

sed -n 's/Bayesian Information Criterion: *//p' file

VT F R4

CodePudding user response:

You can use awk to print what you want. By default the delimiter is space, so awk '{ print $4 }' will do the work in your case.

➜ echo 'Bayesian Information Criterion: VT F R4' | awk '{ print $4 }'
VT F R4
  • Related