Extract data from a long string

Hi !

I am trying to check for memory usage on an OrangePi, and publish it via mqtt.

Using the 'free' command in a terminal window gives me this:

          total        used        free      shared  buff/cache   available

Mem: 1023520 412268 107408 11524 503844 655444
Swap: 511756 9216 502540

Using the same command in an exec node, I get the same result as a string:
total used free shared buff/cache available
Mem: 1023520 446516 67600 11528 509404 621192
Swap: 511756 9216 502540

How to extract certaing value from this string?
Like if I would like to extract the free memory?

You can pull the whole output of free into Node-red and process it there, but I would just retrieve the single value from the command line.

For free memory I would exec this command free | awk '/Mem/ {print $4}'
To explain the awk syntax:

  • /Mem/ - select the line[s] which contain "Mem"
  • {print $4} - Print the fourth field (seperated by white space)

On my Raspberry free gives

              total        used        free      shared  buff/cache   available
Mem:        1916084      246080     1069332       27524      600672     1561896
Swap:       1916080           0     1916080

free | awk '/Mem/ {print $4}' gives the string

1069332
1 Like

Or if you want all readings in an object you could run the string through a function node using

let lines = msg.payload.split(/\n/);
let names = lines[0].split(/\s+/).slice(1);
let mem = lines[1].split(/\s+/).slice(1);
let swap = lines[2].split(/\s+/).slice(1);
msg.payload = {};
names.forEach((str, index) => {
    if(mem[index]) msg.payload["mem_" + str] = Number(mem[index]);
    if(swap[index]) msg.payload["swap_" + str] = Number(swap[index]);
})
return msg;

Output

{ 
  "mem_total":3838148,
  "swap_total":511996,
  "mem_used":2890444,
  "swap_used":343064,
  "mem_free":162616,
  "swap_free":168932,
  "mem_shared":4452,
  "mem_buff/cache":785088,
  "mem_available":719420
}

Wow, that works perfectly on the OrangiPi also. Super, thank for your help !!!

1 Like

I admire anyone, who can just spit out codes lik this :slight_smile:

Thank you for your help !

1 Like

Nice, though I can't tell by inspection what the slice(1) bit does.
By experiment: it throws away array[0] ( "", "Mem:" or "Swap:")

I am slightly disappointed there were no silicon pixies in this answer! :rofl:

1 Like