0

Hi I'm currently writing shell script and need to get the value from a column when the next column matches a value. An example of the output to be search is below.

con1{649}:  AES_CBC_256/HMAC_SHA2_256_128/MODP_2048, 306081 bytes_i, 444452 bytes_o, rekeying in 6 minutes

So in the above output I'm look to extract the "306081" but as the column can move I want to grab the column befores value of "bytes_i"

I've tried the following but it fails to return as value ipsec statusall | grep con1{ | awk -v b="bytes_i" '{for (i=1;i\<=NF;i++) { if ($i == b) { print i } }}

I was thinking if I could get the colume number of bytes_i I could subtrack 1 and then use awk to grab that column value but I'm open to suguestions.

gudok
  • 4,029
  • 2
  • 20
  • 30

2 Answers2

0

I'm sure there is probably a more optimal way to do this but I've managed to solve it with the following shell script. The following function in my code with $1 being the connection to look for and $2 is the value I was looking for to get the number before it.

ipsec_get_bytes()
{
  for ipsec in $(ipsec statusall | grep $1\{ | grep bytes_ | tr -su ' ' '\n' | tail -n +2)
  do
    if [ "$ipsec" == "$2" ] || [ "$ipsec" == "$2," ]; then
      echo $ipsec_prev
      break
    else
      ipsec_prev=$ipsec
    fi
  done

}
0

You could use sed with back-references:

ipsec statusall | sed -n 's/\(.*\) \([0-9]*\) \(bytes_i.*\)/\2/p'

This will return the numeric string that immediately precedes bytes_i.

fuzzydrawrings
  • 283
  • 2
  • 6