Shell – how can we use awk to get multiple words after a significant word

awkshell-scripttext processing

I want to connect to my DB only once to do multiple SELECT queries as follows:

#!/bin/bash
#Begin Code
query=$(echo "SELECT COUNT(*) from USER_IPTable;
      SELECT User from USER_IPTable;
      SELECT IP_Address from USER_IPTable;" | mysql -u root --password='PASS' MatchingDB)

this will return something like that:

COUNT(*) 3 User user1 user2 user3 IP_Address 192.168.1.17 192.168.1.24 192.168.1.17

I have managed to get the COUNT by using awk as follows:

numberOfUsers=$(echo $query| awk ' { print $2 } ')

my question is how can I use awk to get every word after the word User according to the count and to get every word after the word IP_Address according to the count too?

Best Answer

I would try something like that :

for i in `seq 1 $numberOfUsers`;
do
    #Will print users
    echo $query | awk ' { print `expr $i + 2` } '
    #Will print ip
    echo $query | awk ' { print `expr $i + $numberOfUsers + 3` } '
done 
Related Question