Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

read text file two words at a time in a loop in bash

I have a text file with a space separated list of numbers (lat/lon) that looks like this :

-8.000 43.860 -9.000 43.420 -9.350 43.220 -9.388 42.893 -9.000 42.067 -8.935 41.308 -9.000 40.692 -9.278 40.000 -9.324 39.550 -9.518 39.387 -9.777 38.883 -9.285 38.378 -8.909 38.293 -8.951 38.000 -8.965 37.953 -8.917 37.833 -8.913 37.667 -8.915 37.500 -8.975 37.333 -9.017 37.167 -9.045 37.000

I know how to loop through the numbers one by one in bash like this

awk '{ for ( i = 1; i < NF; ++i ) print $(i); }' example.txt |
while IFS= read -r lon lat
do 
    echo processing: "$lon $lat" 
done

giving:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

processing: -8.000 
processing: 43.860 
processing: -9.000 
processing: 43.420 
processing: -9.350 
processing: 43.220 

etc, but how can I loop through the file pair-wise?

i.e. something like (but this obviously doesn’t work):

while IFS= read -r lon lat
do 
    echo processing: "$lon $lat " 
done

to give me lon=-8, lat=43.86 on the first loop etc…?

>Solution :

You can read all the fields in a line into an array (with read -a), and then loop over that:

while read -r -a fields; do
    for ((i=0; i < ${#fields[@]}; i += 2)); do
        echo "${fields[i]}" "${fields[i+1]}"
    done
done < example.txt
-8.000 43.860
-9.000 43.420
-9.350 43.220
...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading