Bash Command to Get Nth Line in a String?

hi

i need to get the 3rd line in a string.

actually, not sure if it's a string, list, array, or something else. I'm using grep to retrieve all the numbers in a string-- in the console, it displays as multiple lines:

$ echo "Sink 0: reference = 0: 153% 1: 45%, real = 0: 62%" | grep -o [0-9]* 
0
0
153
1
45
0
62

now i want to retrieve just the 3rd number in the list (153 in this case). How?

full disclosure, my source string is actually the output of another command, but wanted to keep the question simple.

btw, If there's a simpler way to retrieve the 3rd number in the original string, plz share. But note that there are embedded line-breaks in my actual source string (with which the above grep method has no problem).

thx!

(also asked on linuxforums.org)

Try

echo "Sink 0: reference = 0: 153% 1: 45%, real = 0: 62%" | sed -r 's/[^0-9]+/\n/g;s/^([^\n]*\n){3}//g;s/\n([^\n]*\n){4}$//'
153

Hi, under bash:

$ readarray -s2 BOB < <(echo "Sink 0: reference = 0: 153% 1: 45%, real = 0: 62%" | grep -o "[0-9]*")
$ echo $BOB
153

with "-s2" for line number 3

1 Like

Or

$ echo "Sink 0: reference = 0: 153% 1: 45%, real = 0: 62%" | awk -F ': ' '{print $3+0}'
153

or, shell only:

var="Sink 0: reference = 0: 153% 1: 45%, real = 0: 62%"
var2=${var#*: *: }
echo "${var2%%%*}"

--
Note: With sed, -r , [^\n] and \n in the replacement part are GNU extensions.
Note: readarray is bash 4 or higher...

1 Like
 pacmd dump-volumes | awk -F': *' '/^Sink 0/{print 0+$3}'