50

I need to remove the last character from a string in this command:

sudo docker stats --no-stream 39858jf8 | awk '{if (NR!=1) {print $2}}'

The result is 5.20% , I need remove the % at the end, giving 5.20. Is it possibile to do this in the same command?

Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501
Steph
  • 547
  • 1
  • 4
  • 6

1 Answers1

87

Yes, with substr() you can do string slicing:

... | awk '{if (NR!=1) {print substr($2, 1, length($2)-1)}}'

length($2) will get us the length of the second field, deducting 1 from that to strip off the last character.

Example:

$ echo spamegg foobar | awk '{print substr($2, 1, length($2)-1)}'
fooba
heemayl
  • 54,820
  • 8
  • 124
  • 141