I have a paste command in my script. But it is not giving my desired output. my datafile is
file.txt
1
3
5
4
my shell script is
f1=file.txt
for j in 1..12
do
awk '{printf ("%.1f\n", $1+'$j');}' $f1 > $j_$f1
paste $j_$f1 > ofile.txt # ofile.txt is a new empty file
done
This script gives output as
ofile.txt
2
4
6
5
3
5
7
6
.
.
My desired output as
ofile.txt
2 3 4 5 6 ... 13
4 5 6 7 8 ... 15
6 7 8 9 10 .. 17
5 6 7 8 9 ... 16
I also want to do for the following script
bonus_company1=10
bonus_company2=25
bonus_company3=50
declare var=("company1" "company2" "company3")
for k in var{[@]}
do for j in jan..dec
do if [ $j == "jan" ] || [ $j == "may" ] || [ $j == "sep" ]; then
awk '{printf ("%.1f\n", $1+ '$bonus_$k');}' $f1 > $k_$j_$f1
elif [ $j -ne "jan" ] && [ $j -ne "may" ] && [ $j -ne "sep" ]; then
awk '{printf ("%.1f\n", $1+5);}' $f1 > $k_$j_$f1
fi
paste $k_$j_$f1 > $k.txt # $k.txt is a new empty file
done
done
so I will get 3 different files for three companies. e.g
company1.txt
11 6 6 6 11 .....
13 8 8 8 11 .....
15 10 10 10 15 .....
14 9 9 9 14 .....
I would suggest doing the whole thing in awk, rather than using a shell loop:
awk '{for (i=1; i<=12; ++i) printf "%d%s", $1+i, (i<12?FS:RS)}' "$f1" > output
This loop runs for each line of the file and outputs all of the columns, saving the need to use another tool such as paste. The ternary operator is used to output a space (FS) between each column and a newline (RS) at the end of the line.
For the second part of your question, you can still do most of the work in awk.
declare -A companies
companies=( [company1]=10 [company2]=25 [company3]=50 )
for c in "${companies[@]}"; do
awk -v bonus="${companies[c]}" '{for (i=1; i<=12; ++i)
printf "%d%s", $i+(i==1||i==5||i==9?bonus:5), (i<12?FS:RS)}' "$f1" > "$c.txt"
done
I have created an associative array containing each company name and their bonus. The loop goes through each company in the array, passing the bonus to awk as a variable (note that I'm doing this using -v rather than using string concatenation). The loop goes from 1 to 12, adding the bonus for months 1, 5 and 9, or 5 otherwise. The name of the company (the key of the shell array) is used for the output file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With