user2854333 user2854333 - 1 year ago 46
Bash Question

Even and Odd lines based assignment to variable

I am trying to read the data from data from txt file. Below is the content of txt file.
google is working
Yahoo is working

I am trying to assign the odd lines to variable A and even to variable B. So that I can run following command.

curl -s | grep -Po 'google is working'
curl -s | grep -Po 'Yahoo is working'

I was trying to get it done using variable so that odd lines are automatically passed in curl and even in grep

curl -s $A | grep -Po $B

But I am unable to read the values and store it in variable.

Any suggestion will be of great help.

Answer Source

Below is a simple while loop which should provide you with the required solution you are looking for.

while read -r odd_line
    echo "Odd line" $odd_line
    read -r even_line
    echo "Even line" $even_line
    curl -s "$odd_line" | grep -Po "even_line"
done < temp.txt

How it works temp.txt is the file which contains you're data. This while loop reads temp.txt one line at a time. As expected, first line will be odd odd_line variable will hold odd line. Calling read again inside while loop will read even line. So even_line variable will contain even line. Once you have both variables define, you can pass them to any command