Bash – Processing bash variable with sed

bashscriptingsedshellshell-script

bash variable LATLNG contains a latitude & longitude value in brackets like so

(53.3096,-6.28396)

I want to parse these into a variable called LAT and LON which I'm trying to do via sed like so

LAT=$(sed "s/(\(.*\),\(.*\))/\1/g" "$LATLNG")
LON=$(sed "s/(\(.*\),\(.*\))/\2/g" "$LATLNG")

However, I get the following error:

sed: can't read (53.3096,-6.28396): No such file or directory

Best Answer

This can be solved via pure shell syntax. It does require a temp variable because of the parentheses (brackets) though:

#!/bin/bash

LATLNG="(53.3096,-6.28396)"

tmp=${LATLNG//[()]/}
LAT=${tmp%,*}
LNG=${tmp#*,}

Alternatively, you can do it in one go by playing with IFS and using the read builtin:

#!/bin/bash

LATLNG="(53.3096,-6.28396)"

IFS='( ,)' read _ LAT LNG _ <<<"$LATLNG"
Related Question