-2

I need your help/pointers on extracting couple of words through regex. I have a line that is stored in a file (line shown below). I need to extract the values of two words (time and interface) and store them in a variable for further calculations.

{"record-type":"int-stats","time":1389309548046925,"host-id":"a.b.c.d","interface":"ab-0/0/44","latency":111223} 

So the values of time and port needs to be stored in two different variables.

Cœur
  • 37,241
  • 25
  • 195
  • 267
spamulap12
  • 97
  • 1
  • 9

3 Answers3

1

assuming that you are looking for "pure" shell scripts and not perl or python or programs what are generally not bundled with the os, here is something you could do:

#!/bin/sh

JFILE=a.json
TIME=$(egrep -o '"time":[0-9]+' $JFILE | cut -d: -f2)
IFACE=$(egrep -o '"interface":"[a-z0-9/\-]+"' $JFILE | cut -d: -f2 | sed -e 's/"//g')

echo "time = $TIME"
echo "interface = $IFACE"
bh45k4r
  • 26
  • 2
  • Thanks a lot! This works great. Now, I have the above line repeating after certain number of lines in the same file. I want to extract the time and port fields of these lines. The port value will be the same but, the time value changes. How can I do it? Addind @jaypal here – spamulap12 Feb 19 '14 at 19:39
0

If you can use awk then may be this could be of help:

$ string='{"record-type":"int-stats","time":1389309548046925,"host-id":"a.b.c.d","interface":"ab-0/0/44","latency":111223}'
$ time=$(awk -F[:,] '{ print $4 }' <<< "$string")
$ interface=$(awk -F[:,] '{ gsub(/\"/,"");print $8 }' <<< "$string")
$ echo "$time"
1389309548046925
$ echo "$interface"
ab-0/0/44
jaypal singh
  • 74,723
  • 23
  • 102
  • 147
0

you can make use of arrays. e.g.

#!/bin/sh

JFILE=a.json
TIME=(`egrep -o '"time":[0-9]+' $JFILE | cut -d: -f2 | tr '\n' ' '`)
IFACE=(`egrep -o '"interface":"[a-z0-9/\-]+"' $JFILE | cut -d: -f2 | sed -e 's/"//g' | tr '\n' ' '`)

i=0

for each in ${TIME[@]}
do
    echo "TIME[$i] = $each"
    let i++
done

see Arrays in unix shell? for more about arrays.

Community
  • 1
  • 1
bh45k4r
  • 26
  • 2