0

I have to add up rows and choose columns. I want to use

File

1 2 3
1 2
1

with no arguments the script should return

6 (1st row)
3 (2nd row)
1 (3rd row)

Here's the code for this part that I made:

awk '{ for(i=1; i<=NF;i++) sum+=$i; print(sum); sum=0 }' $FILE

with argument 1 and 2 (number of columns), the script should add every row in column 1 and 2 so it should return:

3 (1st+2nd column)
3 (1st+2nd column)
1 (1st+2nd (blank) column))

The only thing that I need is a condition to sum only certain rows

2 Answers 2

0

you can pass variables to awk and you command would look like this:

awk -v col1=1 -v col2=2 '{ for(i=1; i<=NF;i++) {if (i == $col1 || i == $col2 ) sum+=$i}; print(sum); sum=0 }' $FILE
  • -v var=value assigns value to program variable var.

you can add as much columns as you want just add -v colx=value, then add ot to the condition || i == $colx

If you want to pass the columns number to shell script, you can add them into an array let's say columnsArray, then create a variable columns=$(echo "${columnsArray[@]}"), then your command should look like this:

awk -v outCols="$columns" 'BEGIN{split(outCols, cols, " ")} { for(i=1; i<=NF;i++) {if (i in cols ) sum+=$i}; print(sum); sum=0 }' $FILE

for example

#!/bin/bash
columns=$(echo "$@")
awk -vcolss="$columns" 'BEGIN{split(colss, cols, " ")}{ for(i=1; i<=NF;i++) {if (i in cols ) sum+=$i}; print(sum); sum=0 }' test

would return:

3
3
1
6
  • And is there any way to pass certain columns I want to add? So when I make ./sum.sh file.txt 1 2 it will add first and 2nd columnd but ./sum.sh file.txt 1 will add only 1st column and ./sum.sh file.txt 2 3 will add 2nd and 3rd column and return 5 (1st row), 2 (2nd row), 0 (3rd row)
    – mikro098
    Dec 22, 2016 at 10:07
  • something like this doesn't work: ` awk -v x="$1" '{ for(i=1; i<=NF; i++) {if (i == $x) sum+=$i}; print(sum); sum=0}' $PLIK` I'm waiting for you editing the post
    – mikro098
    Dec 22, 2016 at 10:14
  • Something like this doesn't work: colmuns=$(echo "${tablica[@]}") awk -v columns="$columns" '{ for(i=1; i<=NF;i++) {if (i in columns ) sum+=$i}; print(sum); sum=0 }' $FILE when I type ./sum.sh file.txt 1 2 there is an error
    – mikro098
    Dec 22, 2016 at 10:26
  • It still doesn't work. When I execute the script ./sum.sh file.txt 1 2 3 it returns the same as I would type ./sum.sh file.txt 1 2.
    – mikro098
    Dec 22, 2016 at 10:43
  • 1
    I've posted my answer. Anyway thanks for help!
    – mikro098
    Dec 22, 2016 at 12:08
0

Ok, there is answer I wanted to achieve:

    #!/bin/bash
    PLIK=$1
    shift
    d=${@}
    awk -v c="$d" 'BEGIN {split(c,a," ")}{c=0; for(i in a) c+=$a[i]; print c}' $FILE

./script.sh file.txt 1 2 will return 3 3 1 and ./file.sh file.txt 2 3 will return 5 2 0 which is correct

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .