You can use awk
data=$(nc localhost 12000 | awk -F"[.,]" '/GPRMC/ {print $2}')
echo $data
134129
This will connect to port 12000
on localhost
and if it gets data automatically from this, you can parse it trough awk
sed
or other program
Question
i want to create a bash script that grep a specific value from a socket
The data, i get from the socket is like this:
$GPGSV,4,3,14,16,19,14,30,,,25*7834128.000,V,N*4D
$GPRMC,134129.000,V,5309.2672,N,00811.8483,E,0F
$GPGGA,1341299,99.9*09
I want to get the information between $GPRMC,
and 000
can i use the nc
-command with sed
for this?
Solution
You can use awk
data=$(nc localhost 12000 | awk -F"[.,]" '/GPRMC/ {print $2}')
echo $data
134129
This will connect to port 12000
on localhost
and if it gets data automatically from this, you can parse it trough awk
sed
or other program
OTHER TIPS
nc -l | sed -n 's/^\$GPRMC\(.*\)000.*/\1/p'
with only a grep but need certainly to specify a more exact pattern limit (like 000, to avoid any string longer if another 000 is in the string) If only first 000 is the limit, sed action need to change a bit
If the output of nc -l
is not large and you want the value in a variable, use a read loop:
while IFS=., read match GPRMC _; do
[[ $match = '$GPRMC' ]] && break
done < <(nc -l)
# Value is in "$GPRMC"
Note: if no matching line is found, the last line output by nc -l
will be used.
You could try something like :
[ ~]$ cat test.txt
$GPGSV,4,3,14,16,19,14,30,,,25*7834128.000,V,N*4D
$GPRMC,134129.000,V,5309.2672,N,00811.8483,E,0F
$GPGGA,1341299,99.9*09
[ ~]$ sed -n 's/.*\$GPRMC,\([0-9]*\)\.000.*/\1/p' test.txt
134129
You could use awk
too :
[ ~]$ awk -F "[,.]" '($0 ~ "\\$GPRMC,.*\\.000"){print $2}' test.txt
134129
If you want to catch the result of a command into a variable :
[ ~]$ var=$(cmd)
[ ~]$ var=`cmd`
int x = 0, cmp = 0;
char str[]="$GPRMC,220516,A,5133.82,N,00042.24,W,173.8,231.8,251114,004.2,W*70";
char *str1;
char url[300];
strcpy (url,"?");
str1 = strtok(str, ",");
cmp = strcmp (str1, &"$GPRMC");
if(cmp == 0)
{
while (x < 12)
{
str1 = strtok(NULL, ",");
if (str1 == NULL)
{
x++;
}
else
{
x++;
switch(x)
{
case 1:
strcat (url,"tm=");
strcat (url,str1);
break;
case 3:
strcat (url,"<=");
strcat (url,str1);
break;
case 5:
strcat (url,"&ln=");
strcat (url,str1);
break;
case 9:
strcat (url,"&dt=");
strcat (url,str1);
break;
}
}
}
strcat (url,"&fl=0");
strcat (url,"&en=0");
printf("%i: %s\n", x, url);
}
getch();
Would
nc -l | grep "GPRMC" | sed "s/.GPRMC,//" | sed "s/.000.*//
work for you?