Print out a statement before each output of my scr

2019-09-02 04:39发布

问题:

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?

回答1:

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


标签: bash unix grep