realKSMC
realKSMC

Reputation: 115

How to interpret coordinates using shell script?

We got an file called coords.txt where tons of coordinates are listed. We'd like to read them line by line and do something with them, but we need to set x, y and z first.

coords.txt:

0, 0, 0
1, 1, 1
232, 434, 434
644, 322, 112

shell.sh EDIT:

coord_reader='^[0-9], [0-9], [0-9]'
while IFS='' read -r line || [[ -n "$line" ]]; do
echo $line
    if [[ $line =~ $coord_reader ]]; then

        x=${BASH_REMATCH[1]}
        y=${BASH_REMATCH[2]}
        z=${BASH_REMATCH[3]}
        echo "x is $x, y is $y, z is $z"
else
echo "wrong"
fi

done < "$1"

We start it using bash shell.sh coords.txt

Looks like there is an issue in the coord_reader, I get just an result for x.

I am new to stackoverflow, feel free to comment so I can improve my asking skills.

Upvotes: 0

Views: 298

Answers (2)

Raman Sailopal
Raman Sailopal

Reputation: 12887

awk -F, '$0 ~ /^([[:digit:]]+),[[:space:]]([[:digit:]]+),[[:space:]]([[:digit:]]+).*$/ { print "x="$1" y="$2" z="$3 }' coords.txt

Another alternative is awk. We pattern match for the regular expression. I notice that there is also a space in before the comma (not sure if this is intentional) If the pattern matches, then print out the string with x=,y=,z= using the relative positioned strings separated using the comma.

Upvotes: 0

chepner
chepner

Reputation: 531948

Your regular expression is only matching single-digit numbers, and you aren't using capture groups. (As an aside, make sure coords.txt properly ends with a newline, so that you don't need the || [[ -n $line ]] hack in your while loop.)

coord_reader='^([0-9]+), ([0-9]+), ([0-9]+)$'

Upvotes: 1

Related Questions