Dave Bedworth
Dave Bedworth

Reputation: 37

read file to variable shell script

I have a text file that has coordinates in it. The text file looks like this:

52.56747345
-1.30973574

What I would like to do within raspberry pi shell script is to read the file and then create two variables. One being latitude which is the first value in the text file and the second being longitude which is the second value. Im not sure how to do this so could i please get some help.

Upvotes: 0

Views: 1070

Answers (3)

signjing
signjing

Reputation: 98

1 You have a data file:

cat data.txt
result: 52.56747345 -1.30973574 42.56747345 -2.30973574 32.56747345 -3.30973574 2 Write a shell script:
cat tool.sh

result:
#!/bin/bash awk '{if(NR%2==0) print $0;else printf $0" "}' data.txt | while read latitude longitude do echo "latitude:${latitude} longitude:${longitude}" done 3 Execute this shell script.Output is like this:

sh tool.sh

result: latitude:52.56747345 longitude:-1.30973574 latitude:42.56747345 longitude:-2.30973574 latitude:32.56747345 longitude:-3.30973574

Upvotes: 0

George Vasiliou
George Vasiliou

Reputation: 6335

This works ok:

$ { read lat;read lon; } <file

First line is stored in var $lat, second line in var $lon

Upvotes: 2

Mark Setchell
Mark Setchell

Reputation: 207365

lat=$(head -1 file.txt)
echo $lat
52.56747345

lon=$(tail -1 file.txt)
echo $lon
-1.30973574

Upvotes: 0

Related Questions