LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (https://www.linuxquestions.org/questions/linux-general-1/)
-   -   inputting values into variables for math from the command line? (https://www.linuxquestions.org/questions/linux-general-1/inputting-values-into-variables-for-math-from-the-command-line-839812/)

dave247 10-22-2010 12:32 PM

inputting values into variables for math from the command line?
 
Hey I am working with shell scripting. I'm using bash under Debian 5.

I am trying to do simple math to find a percentage of files in a folder with a certain name. Anyway to simplify the explanation of what I am looking for, lets say im trying to find the percentage of files with the letter "A" in the name within a folder.

What I thought of to do is this, which finds all the files with "A" in the name, then counts the output lines which gives me the total number of files:
Code:

find . -iname "*A*" | wc -l
This is the only way I can think of to get that number. Now I want to work with that number by dividing it by the total number of files in that directory, which is not a static number; but for this case lets say its 50 files. How can I input that number to a variable that I can use to do the math?

I tried this:
Code:

count << find . -iname "*A*" | wc -l
and then I go into the programming functions of bash where I can write more lines of code, but thats the point I get lost.

Can anyone help me?

MensaWater 10-22-2010 01:05 PM

You should set variables with equal rather than redirect:
Code:

count=$(find . -iname "*A*" | wc -l)
The above sets count variable to the result of the command line in the parentheses. (It could also be done by using backticks instead and no dollar sign but many say that shouldn't be used any more.)

bash and most shells have built in math functions but typically don't do floating point so may not round where you want. I usually use the bc (binary calculator) command for math unless it is simple addition or subtraction.

So to determine 50% of the number I'd do something like:
Code:

halfcount=$(/bin/echo $count \* .5 |bc -l)
You need the backslash in front of the asterisk (which is multiplication in bc) to prevent it from being seen as a meta character matching all files. The "-l" option of bc tells it to do floating point output.

The above doesn't actually output the value but rather sets a new variable called halfcount. To see the value you simply do "echo $halfcount"

dave247 10-22-2010 01:50 PM

wow thanks Mensa, that looks helpful. i will have to toy with that more when I get home from work tonight. i appreciate the help


All times are GMT -5. The time now is 02:22 PM.