Search code examples
linuxfileawk

awk print to file is appending not overwriting


i have an awk script that i need to write the output of a command to a file. and it should be overwriting the value in the file so there is only one value. but it is appending, giving me 1000 readings instead of just 1. i am stumped.

for (i = 0; i < 1000; i++) {
  getline < COMMAND
  MIN2 = $1
  close(COMMAND)

  print MIN2 > "lastValue.txt"
}

to be clear: the script otherwise works perfectly. i just need it to OVERWRITE, NOT APPEND. and to my eyes, that's what the > does. if i had >> i would expect it to append, so i'm lost as to why the > is doing what >> should do.


Solution

  • You're thinking of the semantics of > in shell, awk is not shell and so, among other things, > doesn't mean the same in awk as it does in shell.

    An awk script like:

    for (i=1; i<=5; i++) {
        print i > "file"
    }
    

    is not the same semantics as a shell script like:

    a)

    for (( i=1; i<=5; i++ )); do
        echo "$i" > file
    done
    

    where the shell [re-]opens the output file in every loop iteration, it's the same as a shell script like this:

    b)

    for (( i=1; i<=5; i++ )); do
        echo "$i"
    done > file
    

    where the shell only opens the output file once, when the loop starts.

    If you want an awk script to do what shell script "a)" above does, it'd be:

    for (i=1; i<=5; i++) {
        print i > "file"
        close("file")
    }
    

    which for your code would be:

    for (i = 0; i < 1000; i++) {
      getline < COMMAND
      MIN2 = $1
      close(COMMAND)
    
      print MIN2 > "lastValue.txt"
      close("lastValue.txt")
    }
    

    but I can't come up with a reason why you'd want to write to a file 1000 times and then discard the first 999 lines instead of only writing to it once when you're done:

    for (i = 0; i < 1000; i++) {
      getline < COMMAND
      MIN2 = $1
      close(COMMAND)
    }
    print MIN2 > "lastValue.txt"