User6789
User6789

Reputation: 15

How do I append awk script to a file?

hello i have the following awk script:

#!/bin/awk -f 

{for(i=4;i<=7;i++) j+=$i;  print "Student",NR",",$1,$2",",j/4; j=0} 

and i want to append the output to a new file (newfile.txt).

Upvotes: 1

Views: 53

Answers (2)

Ed Morton
Ed Morton

Reputation: 203665

Don't use a shebang to call awk from a shell script as it robs you of the ability to separate your functionality by what each (the shell or awk) does best. Make your shell script look like this instead (using whichever shell you use for the shebang):

#!/bin/env bash

awk '
{for(i=4;i<=7;i++) j+=$i;  print "Student",NR",",$1,$2",",j/4; j=0}
' "$@" >> newfile.txt

Upvotes: 1

RavinderSingh13
RavinderSingh13

Reputation: 133538

Could you please try following. Where mention output file inside awk code itself.

{for(i=4;i<=7;i++) j+=$i;  print "Student" OFS NR",",$1,$2"," OFS j/4 >> (output_file); j=0}


OR 2nd way is when you are running your awk code where script is the script name you are calling to run your awk program eg-->

./script >> output_file


In case you want to run an awk one-liner to get output into a output file then try following.

awk -v output_file="Output.txt" '{for(i=4;i<=7;i++) j+=$i;  print "Student" OFS NR",",$1,$2"," OFS j/4 >> (output_file); j=0}' Input_file 

In above code I have created a variable named output_file whose value you could keep it as per your wish too.

Upvotes: 1

Related Questions