1

I have a output of the command df and using cut I have successfully extracted 22%. But the problem is I want only 22 not the %, as I will be comparing the value with another integer variable. How to do it in Bash ?

Sandipan
  • 113
  • Instead of cut-ing out the percentage, you could use

    df --output=pcent / That still requires getting rid of the %, though.

    – markgraf Dec 17 '19 at 10:11

2 Answers2

2

The easiest and fastest is probably to use bash' parameter expansion features, like this:

string="22%"
percentage="${string%\%}"

echo "$percentage"   # Output: 22

In ${string%\%}, the first % has the special meaning: remove from the end of the parameter (the parameter is string in this case).

The second % is what to remove from the parameter. But since the % has a special meaning in this context, it has to be escaped by a \.

For more examples and information see the advanced bash scripting guide chapter 10.

Hkoof
  • 1,667
2

There are many ways on the command line to extract numbers such as linked to the sed or awk tools that are POSIX. However since you inquire directly how to accomplish that with bash. Let us assume we have the a shell variable $VARIABLE which was set to 22% then this code would help you to get only the number 22

user@box:~$ VARIABLE='22%'
user@box:~$ echo "${VARIABLE%%\%}"

ouputs 22

Consider that that somewhat confusingly especially with your example the % character is used here with a special meaning, such as "substitute from the end of the string stored in the sheel variable". To indicate that what should be removed from the end would be the % character literally we have to escape it like this \%

fraleone
  • 797