7

I have a process that filters a list of files from a directory (having find check to see if there are files older than a certain period to show a queue is stuck). It may or may not return anything, and if it does, it is mailed to be by cron.

What I would like to know is if there is a program or simple bash method to pipe this output to, and if there is any output through it, prepend a header line (like "These are the files stuck in the queue").

silvein
  • 113

4 Answers4

8

sed inline answer:

find ./files -mtime +90|sed '1s/^/Files stuck in queue:\n/'
Jodie C
  • 1,879
  • This works, and is what I ended up using. – silvein Mar 09 '12 at 02:13
  • 1
    @silvein: It seems short is your main criterion, so here are a couple of points: camh's awk answer can be tweaked to being only 8 chars longer than sed (above): awk 'NR==1{print "header"}1'... but even shorter than above, by 5 chars, is: sed "1i header" – Peter.O Mar 09 '12 at 03:50
  • @Peter.O As with all things Unix-y, there are multiple ways to do something. But the likelihood that I can remember it increases if it is shorter. – silvein Mar 13 '12 at 18:10
5

Since the other methods don't actually provide a bash method, as was asked for:

command | while IFS= read -r line; do
    (( i )) || { printf '%s\n' 'These are the files stuck in the queue:' ; (( i++ )) ; }
    printf '%s\n' "${line}"
done

All of the commands used are internal to bash.

If there are no lines of output, nothing will be printed. If there are, the header line will be printed, and then the output from command.

Chris Down
  • 125,559
  • 25
  • 270
  • 266
4

When I find I want to keep state when processing an input stream, I find awk is often the best tool to use.

In this case, you want to process a stream, and if you see some input, write out a header and record that you have written the header.

awk '!input_seen { print "header"; input_seen = 1 } 1'

This will print a header if the variable input_seen is false (which it defaults to if undefined) and sets it to a truth value (1). The 1 at the end is another rule which is a short-hand way of saying: print the current line - you could also replace the 1 with { print }.

camh
  • 39,069
0

Or,

output=$(command)
[[ -n $output ]] && { echo "header"; echo "$output"; }
glenn jackman
  • 85,964