4

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?

4
  • cat /home/reviews_folder/* | tr -s ' ' '\n' | grep - c '<Author>' | sort? Commented Feb 8, 2019 at 14:50
  • Your current code doesn't appear to output filenames, just the counts. Also - c' looks like a typo Commented Feb 8, 2019 at 14:50
  • @Biffen You don't need the parentheses; a for loop is a command by itself. Commented Feb 8, 2019 at 15:07
  • Yeah I hadn't put in the code to output the filenames, but honestly I've been trying for a couple hours and can't figure out how. I was think it's something like | sort & & echo basename $FilePath but am not sure how to arrange it Commented Feb 8, 2019 at 17:59

1 Answer 1

5

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.