Svend Bager
Svend Bager

Reputation: 11

Edit multiple files using awk

I am trying to edit multiple files using awk in the following way:

awk '{F = FILENAME ".inp"; print $0 > F ; if(NR==3) print  "%moinp usr/speciale/br/brhgooh/scan/newscan/freqBZ/cas/prov2/",FILENAME  > F }' *.xyz

It works well with the first file, but in the rest of the files the change does not appear.

Any suggestions?

Upvotes: 0

Views: 57

Answers (1)

glenn jackman
glenn jackman

Reputation: 247072

You need to use FNR not NR

  • NR is the record number of all records seen thus far
  • FNR is the record number of the current file

Adding some whitespace helps readability:

awk '
    BEGINFILE {
        close(F)
        F = FILENAME ".inp"
    }
    {print > F}
    FNR == 3 {print "%moinp usr/speciale/br/brhgooh/scan/newscan/freqBZ/cas/prov2/" FILENAME  > F }
' *.xyz

If your awk does not have BEGINFILE, you can use FNR == 1 instead.

Other changes:

  • print instead of print $0 ($0 is the default)
  • print "%mo .../" FILENAME without a comma -- a comma will insert a space after the slash.
  • close(F) to prevent "too many open files" errors

Upvotes: 1

Related Questions