0

I have a script that checks each file in a folder for the word "Author" and then prints out the number of times, one line per file, in order from highest to lowest. In total I have 825 files. An example output would be

53
22
17

I want to make it so that I print out something before each number on every line. This will be the following hotel_$i so the above example would now be:

hotel_1 53
hotel_2 22
hotel_3 17

I have tried doing this using a for loop in my shell script:

for i in {1..825}
do
    echo "hotel_$i"
    find . -type f -exec bash -c 'grep -wo "Author" {} | wc -l' \; | sort -nr
done

but this basically prints out hotel_1, then does the search and sort for all 825 files, then hotel_2 repeats the search and sort and so on. How do I make it so that it prints before every output?

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
John Smith
  • 679
  • 1
  • 9
  • 17
  • Do you always want to search for the same string in the same directory 825 times? This doesn't make much sense. Can you explain your use case more or show a more realistic example? – Will Feb 15 '16 at 23:29
  • I can't help but notice that you ask many related questions, and I don't think the end result will be ideal; see [here](http://stackoverflow.com/questions/35416492/how-do-i-write-a-unix-script-which-counts-the-number-of-reviews-in-a-file), [here](http://stackoverflow.com/questions/35418255/how-to-make-a-shell-script-take-an-argument-passed-in-the-command-line) and [here](http://stackoverflow.com/questions/35419722/how-to-make-my-shell-script-check-every-folder-in-a-directory-for-a-word-and-the). – Benjamin W. Feb 15 '16 at 23:31

1 Answers1

2

You can use the paste command, which combines lines from different files:

paste <(printf 'hotel_%d\n' {1..825}) \
<(find . -type f -exec bash -c 'grep -wo "Author" {} | wc -l' \; | sort -nr)

(Just putting this on two lines for readability, can be a one-liner without the \.)

This combines paste with process substitution, making the output of a command look like a file (a named pipe) to paste.

The first command prints hotel_1, hotel_2 etc. on a separate line each, and the second command is your find command.

For short input files, the output looks like this:

hotel_1 7
hotel_2 6
hotel_3 4
hotel_4 3
hotel_5 3
hotel_6 2
hotel_7 1
hotel_8 0
hotel_9 0
Benjamin W.
  • 46,058
  • 19
  • 106
  • 116