Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How do I clear the contents of a file before writing to it? For example:

echo one > filename.tmp
# filename.tmp now contains "one"

echo two > filename.tmp
# filename.tmp should now contain "two", not "one" and "two"

My goal is:

  1. Start a listener

    $ nc -l 7007 > /var/tmp/test.log
  2. Send some data

    $ telnet localhost 7007
  3. Test the file

    $ cat /var/tmp/test.log

I don't want "hi" to show up in the log; I want "second_word" to have replaced it

share|improve this question
up vote 3 down vote accepted

You need a separate program to clear and write the new file since nc doesn't offer that option.

nc -l 7007 | while true; do
    while read line; do
      echo "$line" > /tmp/test

You can save everything after the pipe in a separate script that accepts a file path.


while true; do
    while read line; do
        echo "$line" > $1

Then it's simply:

nc -l 7007 | save-last-line.sh /var/tmp/test.log

You'll want to add checks to make sure $1 is writable and show usage when $1 isn't specified.

share|improve this answer
Better use IFS= read -r line to avoid problems. – Stéphane Gimenez Oct 4 '11 at 16:59

command > /path/to/file will clear the file and write the output of command to it.

When you don't want to clear the file, it's command >> /path/to/file.

One thing to be aware of is the noclobber option in your shell. It will prevent you from clearing files with the > operator. You can override the option by using >! instead, or you can unset it with set +o noclobber.

Try this at your command line:

# echo "Hello, " > /tmp/test
# cat /tmp/test
# echo "U&L" > /tmp/test
# cat /tmp/test
# echo "Hello," > /tmp/test
# echo "U&L" >> /tmp/test
# cat /tmp/test
share|improve this answer
I already tried that. But did not worked. Its always making the "samfile.log" larger and larger, i want to have the last content. (i tried redirector same like yours). – YumYumYum Oct 4 '11 at 11:04
You are correct. But i needed nc -l realtime clean same as > redirector – YumYumYum Oct 4 '11 at 11:16
Please see my updates above. section goal – YumYumYum Oct 4 '11 at 11:19

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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