I have a stream of info from a serial input (GPS Antennae) and wish to output that info into a text file on every input (every second in this case) but instead of appending it to the end of the file as > would do after the initial overwrite I would like it to overwrite it every second so only the latest info is displayed.

I have tried \r which achieves the effect in bash but not the output file.

cat /dev/ttyACM0 | grep --line-buffered  -E "GNGGA" | awk 'BEGIN {FS=","};{printf "%s%s\t\t%s%s\t\t%s%s\t%s%s","Time= ",$2,"Lat= ",$3,"Lon= " ,$5,"Alt= " ,$10; fflush(stdout) }' > somefiles.txt

This includes the initial input, a grep to focus on one line and awk to get the specific parts of the info I need, they don't affect the overwrite issue as far as I know.

Time= 155325.00     Lat= 7428.77433     Lon= 82845.15963    Alt= 21.5

This is the output that starts by overwriting the somefiles.txt but then appends until you stop and run the command again.

So is there a way to make only the latest input appear as one line in the text file?



You can print or printf straight to a file within awk, and close it after every write. That would make awk reopen and truncate it on the next print.

awk -vfile=test.out '{print $0 > file; close(file)}'

(Strictly speaking you get a race condition here, another process might try to read the file just between the truncate and write, so it would seem empty (or worse but less likely, partial).)

  • Thanks for that, it works as needed. The race condition is something I'll check when the txt file is accessed to make sure it's there and complete. – pingualoty Apr 7 '17 at 9:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.