Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading