Home > Software engineering >  Reorder output from Awk, sum first
Reorder output from Awk, sum first

Time:06-16

I have the following variable:

results=$(find . -name "$1" -type f | awk '{n  ;print}END{print n " matches found"}')

This is the output I'm getting:

bash$ ./find-file.sh requirements.txt
find: `./LogFiles/WMI/RtBackup': Permission denied
./project-h-squad/requirements.txt: line 11: python-dotenv==0.17.1: command not found
./project-h-squad/requirements.txt
./team-portfolio/requirements.txt
2 matches found

The only problem is that I want to display 2 matches found at the start or the top and the files to be displayed right after. How can I tweak results to accomplish this?

CodePudding user response:

There's no need to use awk for this; just use bash arrays:

#!/usr/bin/env bash

readarray -d '' -t results < <(find . -name "$1" -type f -print0)
printf "%d matches found.\n" "${#results[@]}"
printf "%s\n" "${results[@]}"

The readarray line will robustly store the files returned by find in an array (By using a 0 byte between filenames instead of newline, annoying files with newlines in the name won't break things), prints out the length of the array, and then its contents.

CodePudding user response:

Does this solve your problem?

results=$(find . -name "$1" -type f | awk '{n[$0]=$0} END{print length(n) " matches found"; for(result in n){print n[result]}}')

N.B. "2 matches found" will be printed first but the array isn't sorted, so "team-portfolio/requirements.txt" might be printed before or after "project-h-squad/requirements.txt"

  • Related