4

How to use & ldquo; For & rdquo; In the awk procedure?

 2 years ago
source link: https://www.codesd.com/item/how-to-use-for-in-the-awk-procedure.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

How to use & ldquo; For & rdquo; In the awk procedure?

advertisements

I have a task: Write a script for the summation of integers stored in the file. Form a call script: example: sum a.txt 3 4

The input file can contain several columns of integer. The individual columns are separeted by speces or tabs. The script should sum a appropriate columns and write the result to stdout. So when we have sum a.txt 3 4 we need to add the number of the third and fourth columns file.

So I do this:

#!/bin/bash
array1=( "$@" )
let LA=${#array1[@]}-1
awk '{for(i=1;i<=$LA;i++)y+=$'${array1[i]}'; print y}' a.txt

but I have an error: awk: : 1unexpected character '.'

Please help is there another way to add up the number of columns whose number are given in the procedure call script?

On this forum a got answer to do this the following:

#!/bin/bash
awk -v col1=$2 -v col2=$3 '{sum1 += $col1; sum2 += $col2} END{print sum1,sum2}' $1

but what if we don't know the amount of numbers of columns that will be given in the procedure example: ./sum a.txt 2 3 ... n (maybe I need use for but how?)


You do not need AWK for this. Bash is enough:

$ cat data.txt
1 2 3 4 5 6
7 8 9 10 11 12
13 14 15 16 17 18
$ ./csum.sh $(seq 0 5) < data.txt
21 24 27 30 33 36
$ cat csum.sh
#! /bin/bash
SUM=()
S=0
for N in "$@"; do
  SUM[$S]=0
  ((S++))
done
while IFS=$'\n' read LINE ; do
  COLS=($LINE)
  S=0
  for C in "$@"; do
    SUM[$S]=$(expr ${SUM[S]} + ${COLS[C]})
    ((S++))
  done
done
echo ${SUM[*]}


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK