Like HERE I have a file.csv with numbers in quotes:
"0.2"
"0.3339"
"0.111111"
To round the number (3 decimals) this solutions works great:
printf "%.03f\n" $(sed 's/\"//g' file.csv)
But now I want to store sed 's/\"//g' file.csv
as a variable
var_sed=$(sed 's/\"//g' file.csv);
printf "%.03f\n" ${var_sed}
Doesn't work. The output is
zsh: bad math expression: operator expected at `0.3339\n0.1...'
0.000
So the problem is that var_sed
passes \n
to printf "%.03f\n"
.
The only solution I know is:
var_sed=$(sed 's/\"//g' file.csv);
printf "%.03f\n" $(echo ${var_sed})
- Maybe there is a cleaner way.
- Also I want to put
printf "%.03f\n"
in a function like this:
printf_function () { printf "%.03f\n" $1;}
But this is not working:
printf_function () { printf "%.03f\n" $1;};
var_sed=$(sed 's/\"//g' file.csv);
printf_function ${var_sed}
also printf_function $(echo ${var_sed})
is not working.
____________________________________________________________
Why I try to save the file in a variable? ____________________________________________________________
The truth is that I actually want to put the sed
command in a function. I'm sorry I put this as a variable to (try to) simplify the problem.
My script is
sed_01 () { sed 's/\"$// ; s/^\"// ; s/something_else//g' $1;};
printf_03 () { printf "%.03f\n" $1;};
printf_03 "$(sed_01 file.csv)"
as mentioned in the comments below, it works in bash.
output:
"0.200"
"0.334"
"0.111"
but in zsh the output: is:
printf_03: bad math expression: operator expected at `0.3339\n0.1...'
0.000
printf "%.03f\n" $(echo ${var_sed})
works and notprintf "%.03f\n" ${var_sed}
is because the command substitution$(the comand)
removes all trailing new lines