DevLuke
DevLuke

Reputation: 93

Isolating a substring of a string in shell script

I'm using lynis to audit some AMI's that I'll be using. After lynis has run it writes to /var/log/lynis.log and gives a "Hardening Index" score to assess the overall hardening of the ami.

I get this value by running sudo cat /var/log/lynis.log | grep "Hardening Index"

Which in turn gives me this line:

2017-07-20 10:45:10 Hardening index : [58] [###########         ]

My question is how do I isolate the 58 to be assigned to a variable for an if statement comparison. I was thinking of using sed or regex but as this value will differ dependent on the ami, and could range from 0-100 I can't think of a way of just extracting that value. Any help would be appreciated.

Upvotes: 1

Views: 130

Answers (5)

mop
mop

Reputation: 433

sudo cat /var/log/lynis.log | grep "Hardening [Ii]ndex"|sed -r 's/[^[]*\[([^]]*).*/\1/'

Upvotes: 0

RavinderSingh13
RavinderSingh13

Reputation: 133760

try following awk too once.

awk '{match($0,/Harden[Ii]ng index.[^\]]*/);print substr($0,RSTART+RLENGTH-2,2)}'  Input_file

Upvotes: 0

hsz
hsz

Reputation: 152294

Try with:

sudo cat /var/log/lynis.log | grep "Hardening Index" | sed -r "s/.*?\[([0-9]+)\].*/\1/"

Upvotes: 0

Petr Skocik
Petr Skocik

Reputation: 60143

The computationally cheapest way to do that in a shell is to use the POSIX parameter expansion facilities (scroll to the bottom of the section) to avoid spawning external processes:

$ var='2017-07-20 10:45:10 Hardening index : [58] [###########         ]'
$ var=${var%%\]*} #remove longest endstring starting with ] 
$ var=${var##*\[} #remove longest startstring ending with [
$ echo $var
  58

Upvotes: 2

anubhava
anubhava

Reputation: 786091

You can use awk and even skip your grep and cat like this:

awk -F '[][]+' '/Hardening [Ii]ndex/{print $2}' var/log/lynis.log
58

This awk uses [ or ] as field separator and extract 2nd field for record that matches Hardening [Ii]ndex regex.

To store this in a variable:

var=$(awk -F '[][]+' '/Hardening [Ii]ndex/{print $2}' var/log/lynis.log)

Upvotes: 2

Related Questions