Reputation: 157
Is there any way to port the following python function to an ash-based shell script?
#def degrees_to_cardinal(d):
#dirs = ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE",
#"S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"]
# ix = int((d + 11.25)/22.5)
#return dirs[ix % 16]
Essentially what I need is to convert a value corresponding to a direction (0-360 degrees) to its corresponding 16-point cardinal direction. degrees -> cardinal direction.
I could use a series of if elif elif... but that seems clumsy and inefficient.
Upvotes: 0
Views: 684
Reputation: 1
This version works for me:
#!/bin/ash
awk -v deg="$1" '
BEGIN {
dirs[0]="N" ; dirs[1]="NNO" ; dirs[2]="NO" ; dirs[3]="ONO"
dirs[4]= "O" ; dirs[5]="OSO" ; dirs[6]="SO" ; dirs[7]="SSO"
dirs[8]="S" ; dirs[9]="SSW"; dirs[10]="SW"; dirs[11]="WSW"
dirs[12]="W" ; dirs[13]="WNW"; dirs[14]="NW"; dirs[15]="NNW"
dirs[16]="N"
}
END {
ix = int((deg + 11.25)/22.5)
print dirs[ix]
}' /dev/null
Upvotes: -1
Reputation: 37298
cat degs2dir
#!/bin/ash
awk -v deg="$1" '
BEGIN {
dirs[1]="N" ; dirs[2]="NNE" ; dirs[3]="NE" ; dirs[4]="ENE"
dirs[5]= "E" ; dirs[6]="ESE" ; dirs[7]="SE" ; dirs[8]="SSE"
dirs[9]="S" ; dirs[10]="SSW"; dirs[11]="SW"; dirs[12]="WSW"
dirs[13]="W" ; dirs[14]="WNW"; dirs[15]="NW"; dirs[16]="NNW"
}
END {
ix = int((deg + 11.25)/22.5)
print dirs[ix]
}' /dev/null
chmod 755 degs2dir
degs2dir 237
#output
SW
IHTH
Upvotes: -1
Reputation: 58
Here's something that might suit your needs:
D=N..NNENE.ENEE..ESESE.SSES..SSWSW.WSWW..WNWNW.NNW
d=$((d*2))
n=${D:$(((d/45)*3)):3}
echo ${n//.*}
Where "d" is the degree value
Upvotes: 1
Reputation: 58
It must be said that bash has no real way of handling floating point numbers.
Of course, to get around this you can just multiply 360 by 5 or 10 and then modify the rest of the script accordingly.
Upvotes: 1