7

I'm piping output from clock through sed to remove leading zeroes from numbers. It looks like this:

clock -sf 'S%A, %B %d. %I:%M %P' | sed 's/\b0\+\([0-9]\+\)/\1/g'

That works fine and produces the output I want.

However, when I try to redirect the output to a file, nothing is written to the file. The following does NOT work.

clock -sf 'S%A, %B %d. %I:%M %P' | sed 's/\b0\+\([0-9]\+\)/\1/g' > testfile

Nothing is written to testfile. What am I doing wrong?

3
  • I don't have the clock command on my Linux system, what does it do. Does it produce one line of output and exit, or does it produce continuous output?
    – Barmar
    Commented Sep 1, 2014 at 20:29
  • With these flags it produces continuous output.
    – Semicolon
    Commented Sep 1, 2014 at 20:45
  • Running the second command without the sed pipe (redirecting clock directly into the file) works as expected. Running the second command without -s results in a single line being written to the file, as expected.
    – Semicolon
    Commented Sep 1, 2014 at 20:52

2 Answers 2

7

You're running into an output buffering problem. sed normally buffers its output when not writing to a terminal, so nothing gets written to the file until the buffer fills up (probably every 4K bytes).

Use the -u option to sed to unbuffer output.

clock -sf 'S%A, %B %d. %I:%M %P' | sed -u 's/\b0\+\([0-9]\+\)/\1/g' > testfile
1
  • 4
    -u is a GNU specific option
    – mikeserv
    Commented Sep 1, 2014 at 21:03
2

I was having the same problem while trying to redirect from a streaming output source.

You should use the -u (unbuffered) flag with sed and then PIPE the data instead of appending it with >> operator (>> locks the file and is blocking).

Instead doing the following works

someprogram | sed '/filter/' | tee myfile.txt
1
  • Sorry for taking 6 years to respond. I just checked the dates. Hope it will help someone who comes looking? Commented Mar 25, 2020 at 20:33

You must log in to answer this question.

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