Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort Output of Loop and Display

Tags:

bash

I have a script that loops through a directory and for each file counts the iterations of a certain word. When the script is run the number of iterations is output to the screen for each file. I however would like to first sort the list before it's output.

I know I need to output to sort somewhere, but I'm not sure how to implement this. In a non scripting language I would probably put the output of the loop into an array, but I don't think that's what's meant to be done with Bash.

for f in /home/reviews_folder/*
do
    tr -s ' ' '\n' < $f | grep - c '<Author>'
done

I don't think I would put the sort in the loop, so how would i create a pipeline between the loop and the sort?

like image 920
Edgar Smith Avatar asked Sep 16 '25 23:09

Edgar Smith


1 Answers

A loop is a compound command, and each command in the body of the loop inherits its standard output from the loop. That means you can simply pipe the loop itself to sort.

for f in /home/reviews_folder/*; do
  tr -s ' ' '\n' < "$f" | grep -c '<Author>'
done | sort
like image 51
chepner Avatar answered Sep 19 '25 16:09

chepner