8

I have a bash script where I get the disk usage, for example 60%. How can I remove the % symbol? Using grep or awk?

pmerino
  • 391
  • 1
  • 4
  • 11

5 Answers5

12

There is no need for external tools like tror even sed as bash can do it on its own since forever.

percentage="60%"
number=${percentage%\%}

This statement removes the shortest matching substring (in this case an escaped %) from the end of the variable. There are other string manipulating facilities built into bash. It even supports regular expressions. Generally, most of the stuff you normally see people using tr, sed, awk or grep for can be done using a bash builtin. It's just almost noody knows about that and brings the big guns...

See http://tldp.org/LDP/abs/html/parameter-substitution.html#PSOREX1 for more information.

Holger Just
  • 3,315
  • 1
  • 16
  • 23
6

This should do it:

sed 's/%//'

Pipe your string through it for the best results.

womble
  • 95,029
  • 29
  • 173
  • 228
6

Instead of sed, use tr.

tr -d '%'
JCallicoat
  • 581
  • 3
  • 5
4

sed is one of the easiest ways

sed -i 's/\%//g' fileName
Mike
  • 21,910
  • 7
  • 55
  • 79
2

If the disk usage is in a variable, bash can do the removal as part of a variable substitution:

diskusagepct="60%"
echo "disk usage: ${diskusagepct%\%} percent"  # prints disk usage: 60 percent
diskusagenum="${diskusagepct%\%}"  # sets diskusagenum to 60
Gordon Davisson
  • 11,036
  • 3
  • 27
  • 33