1

I'm trying to process the last line in a file each time its saved. This is what I have so far:

tail -F -n0 '/path/to/foo.txt' |
  grep "." | while read line
    do echo "$line"   
  done

If I drop the grep, I'll get the last line, the first time the script is run, but when the target file is saved to, the entire file will be output, rather then just the new last line (the desired behaviour).

I need grep to strip the returns, as this is most often the last character in these text files. Im finding the above with the output piped to grep, doesn't return anything.

Im a novice here, so any guidance is very much be appreciated.

orionrush
  • 566
  • 6
  • 30
  • Im not sure what the game is here. But a negative vote on a question with no explanation? Stackoverflow used to be a much more amicable environment. What have I've done to warrant it? – orionrush Jun 22 '13 at 01:21

1 Answers1

2

I fear tail just does not work that way. The -f/-F options stream all the data after processing the initial query -n0, and as far as I know, there's no way to just get the last line of the new data using a single tail invocation.

The solution that could work would be rerunning tail every time the file size changes. On Linux you could use inotify subsystem for efficiency, I don't know what's the MacOS equivalent. The general idea would look like:

while inotifywait -e modify /your/file  # this would wait for the next change on Linux
do
    tail -1 | …your processing here…
done
liori
  • 40,917
  • 13
  • 78
  • 105
  • I had hoped that tail's `-F` flag would allow me to process changed to the file in real time. On [Unix&Linuix SE](http://unix.stackexchange.com/questions/80307/diverting-a-file-write-to-process), I was pointed to [this SO thread](http://stackoverflow.com/questions/1515730/is-there-a-command-like-watch-or-inotifywait-on-the-mac) for various OSX file watching utilities (some good options there). It looks like either one sets up a FIFO or tries to detect writes to the file and process each time something like fswatch or launcd detect a change. – orionrush Jun 22 '13 at 11:46