2

I'm getting broken pipe errors from a command that does something like:

ls -tr1 /a/path | awk -F '\n' -vpath=/prepend/path/ '{print path$1}' | head -n 50

Essentially I want to list (with absolute path) the oldest X files in a directory.

What seems to happen is that the output is correct (I get 50 file paths output) but that when head has output the 50 files it closes stdin causing awk to throw a broken pipe error as it is still outputting more rows.

slhck
  • 223,558
  • 70
  • 607
  • 592
Jon
  • 21
  • 1
  • 3
  • Please answer your question using the **answer your question** button below as soon as you can! Then you can even get reputation for it and accept it. – slhck Nov 28 '11 at 17:11
  • I would have, but as a new user I can't do that for another... 5 hours apparently. I wanted to write the answer down so I didn't forget. – Jon Nov 28 '11 at 17:11

1 Answers1

0

Solution from the OP, revision 2


Firstly there is no need to have awk prepend the path to every single file just to throw most of it away. So the awk statement should be the last pipe.

Secondly instead of reversing sorting with ls we can do a standard time sort and use tail to extract the lines we're after. This ensures the pipe remains open for the entire process.

The new command would look like:

ls -t1 /a/path | tail -n 50 | awk -F '\n' -vpath=/prepend/path/ '{print path$1}'
Melebius
  • 1,798
  • 2
  • 18
  • 27
slhck
  • 223,558
  • 70
  • 607
  • 592