1

I wanted to do a for loop for all files with name "r?.???.txt", where ?.??? was a float from 0.000 to 3.999. However, bash does not have integer, as far as I know... That turns into a headache...

I tried to do for tedious for loop with two variables representing the numbers before and after decimal. However, I still need to insert zeros if you have ?.00?. Therefore I will need a proper treatment of float numbers and how to store / output them.

In summary, there are two questions I face

  1. doing float in bash
  2. output that float as a value and pass into filename

Thank you.

Simon
  • 703
  • 2
  • 8
  • 19

2 Answers2

1

Using 2 variables is a good idea.

You can keep the zero padding format with seq -f option :

#!/bin/bash
declare -i int=3;
declare -i dec=1000;

for i in $(seq 1 $int);do
        for j in $(seq -f "%03g" 1 $dec);
                do echo r$i.$j.txt;  # or do find . -name "r$i.$j.txt";
        done;
done;
SLePort
  • 15,211
  • 3
  • 34
  • 44
0

Answer 1) For float calculations you will have to delegate the task to other programs such as bc.

For example:

echo "scale=3;20.8/4 | bc 5.200

For more options you can check:

https://unix.stackexchange.com/questions/40786/how-to-do-integer-float-calculations-in-bash-or-other-languages-frameworks
https://unix.stackexchange.com/questions/76060/perform-floating-point-arithmetic-in-shell-script-variable-definitions
How do I use floating-point division in bash?

to find out filenames having float numbers you can use regular expressions along with find command:

$touch r3.987.txt $find . -regextype sed -regex ".*/r[0-9]\.[0-9]\{3\}.txt$" ./r3.987.txt

regular expression type is that of sed, find . means find in current directory

  • */ => to check only for filenames only and skip the leading directory structure

  • [0-9] matches any digit in range 0 to 9

  • \. means match a dot

  • [0-9]\{3\} means [0-9]{3} to match exactly 3 digits and each digit can be in range 0-9

  • and finally ending in .txt

as for Answer 2) you can get that float value as a string by looping through the output of the find command

$for filename in "$(find . -regextype sed -regex ".*/r[0-9]\.[0-9]\{3\}.txt$")"  
> do  
> echo "Filename is $filename"  
> floatValueAsString=$(echo "$filename" | egrep -o '[0-9]\.[0-9]{3}')  
> echo "Float value as string is $floatValueAsString"  
> done  
Filename is ./r3.987.txt
Float value as string is 3.987
Community
  • 1
  • 1
riteshtch
  • 8,629
  • 4
  • 25
  • 38