Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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


2 Answers 2

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.

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
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

This site is currently not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .