8

I want to have a window open that is just the content of the file file.txt. I do not care which command I use to open it, nano, cat, vi or whatever. I want it to update every time it changes, so if I open it in another window, edit it and save it, the file in the original window will update, kind of like screen. Any suggestions?

I have already tried just having it open a new cat file.txt command every few seconds, but it is very unreliable.

msw
  • 42,753
  • 9
  • 87
  • 112
Patrick Cook
  • 458
  • 12
  • 27

5 Answers5

13

Use

watch cat file.txt

That should update when any changes occur, also try

man watch

To see what options it has so you can update the frequency of the updates.

Dave Mackintosh
  • 2,738
  • 2
  • 31
  • 40
5

The low-tech solution in case watch is not available:

 while sleep 1; do tput clear; cat file.txt; done

(lets you easily adapt the checking interval).

Jens
  • 69,818
  • 15
  • 125
  • 179
3

On Linux, you can use the inotifywait command like so:

#!/bin/sh
while inotifywait --event modify file.txt; do
    tput clear
    cat file.txt
done

which is a modified version of Example 2 in the man page. This has the great advantage of doing absolutely nothing until file.txt is modified. The answers suggesting polling have the problems that polling always does: it will waste time when nothing has changed, and it will fail to catch changes until the polling interval has ended.

msw
  • 42,753
  • 9
  • 87
  • 112
2

If you are on macOS you probably don't have watch installed per standard. You could go for the low-tech solution - which is elegant anyway, but you can also revert to home-brew.

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

You might have to give it (once!) your (administration) password. After the installation finishes, you should always check the system:

brew doctor

There should be a message along the lines:

Your system is ready to brew.

Now you are ready to install watch:

brew install watch

Once that is finished, you are ready for the solution by @dave-mackintosh:

watch cat file.txt

0

Q: How to monitor text file and print output in realtime?

A: tail -F logfile.txt

Outputs the file whenever it is updated.

A2: watch -n 0.1 -t tail -n 3 logfile.txt

Calling watch -n 0.1 means that the command is being executed every 0.1 seconds. The smallest accepted update interval is 0.1. Title is suppressed by -t. Every 0.1 seconds, the last three lines (tail -n 3) are printed.

This is not suitable for high resolution applications.

Hunaphu
  • 589
  • 10
  • 11