1

I want to extract number 26 from res.txt which has :

numid=6,iface=MIXER,name='Speaker Playback Volume'
; type=INTEGER,access=rw---R--,values=2,min=0,max=52,step=0
: values=26,26
| dBminmax-min=-52.00dB,max=0.00dB

I tried

sed -e 's/numid.*values=\(.*\)\,.*/\1/g' res.txt

but that didnt work. Can someone help me with this? I can also use grep or awk to extract.

RDoonds
  • 485
  • 2
  • 6
  • 19

2 Answers2

1

If you have the GNU grep this can be very easily done with it as follows:

grep -oP 'values=\K\d(?=,)' res.txt
redneb
  • 21,794
  • 6
  • 42
  • 54
  • Thanks. Is there a way to store the value in integer in c++ code by running this command line as system("sed -n '/numid/,/: values=/{s/: values=(.*),.*/\1/p}' res.txt") – RDoonds Sep 22 '16 at 00:13
0

Using sed

This prints the first value from the first line that (a) follows a line with numid, and (b) that matches : values=:

$ sed -n '/numid/,/: values=/{s/: values=\(.*\),.*/\1/p}' res.txt
26

How it works:

  • -n

    This tells sed not to print unless we explicitly ask it to.

  • /numid/,/: values=/

    This selects a range of lines that starts with a line matching numid and ends with a line matching : values.

  • s/: values=\(.*\),.*/\1/p

    For those selected lines, this prints the first string after the = and before the ,.

Using awk

$ awk -F'[,=]' 'f && /: values=/{print $2; f=0} /numid/{f=1}' res.txt
26

How it works:

  • -F'[,=]'

    This tells awk to use either , or = as field separators.

  • f && /: values=/{print $2; f=0}

    If the variable f is nonzero and this line matches : values=, then print the second field, $2. Lastly, set f back to zero.

  • /numid/{f=1}

    If the current line matches numid, set variable f to one.

John1024
  • 109,961
  • 14
  • 137
  • 171
  • Thanks. Is there a way to store the value in integer in c++ code by running this command line as system("sed -n '/numid/,/: values=/{s/: values=(.*),.*/\1/p}' res.txt") – RDoonds Sep 22 '16 at 00:14
  • @RDoonds Although c++ is outside of my area, you might look at `popen`. See, for example: ["How to execute a command and get output of command within C++ using POSIX?"](http://stackoverflow.com/questions/478898/how-to-execute-a-command-and-get-output-of-command-within-c-using-posix) or ["How to store system("date +%s) output to variable?c++"](http://askubuntu.com/questions/485134/how-to-store-systemdate-s-output-to-variablec) – John1024 Sep 22 '16 at 00:17