LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Simple bash script help, grabbing part of a string (https://www.linuxquestions.org/questions/linux-newbie-8/simple-bash-script-help-grabbing-part-of-a-string-316917/)

colabus 04-25-2005 06:09 AM

Simple bash script help, grabbing part of a string
 
Hi guys,

Can I get some help?

I want to grab the "81" value in my string.
Code:

/dev/hdb            117217216  93883264  23333952  81% /data
I have gotten it down to:
Code:

$ df|grep /dev/hdb|cut -d"%" -f 1
/dev/hdb            117217216  93883264  23333952  81

I need to grab the first string from the right delimited by " ", any ideas anyone?

ANy help or advice would be great :)

jschiwal 04-25-2005 06:27 AM

Code:

> STRING='/dev/hdb            117217216  93883264  23333952  81% /data'
> echo ${STRING} | cut -f 5 -d" " | sed 's/%//'
81

I used an echo command as the source of the string, but you could probably use a file instead.
The cut command selects the fifth field, while the sed command removes the percent sign.

You might also use an awk filter instead. It is better than sed at selecting fields from the input.

hussar 04-25-2005 07:49 AM

There is also a way to do this with bash's substring removal tools as described in the Advanced Bash Scripting Guide, section 9.2. For example:

bash-3.00$ STRING=`df | grep /dev/hda5`
bash-3.00$ STRING=`echo $STRING | cut -f 5 -d " "`
bash-3.00$ STRING=`echo ${STRING%\%}`
bash-3.00$ echo $STRING
59

(I used my own /dev/hda5 for this example. That's why the result is not 81.)

ahh 04-25-2005 09:42 AM

Here are a couple of different approaches:-
Code:

df | grep /hdb | awk -F " " '{print $5}' | tr -d "%"
df | grep /hdb | sed -e 's/.*[[:digit:]] \+//' -e 's/%.*//'

If it matters, the sed variant will save you a millisecond or so...


All times are GMT -5. The time now is 05:08 AM.