Score:1

Prevent sort from sorting filenames instead of greped content

br flag

In a script, I want to get a variable from find grep and sort to display it with echo on screen. The variable looks like:

OUTPUT="$(find . -maxdepth 2 -type f -name 'filename' | xargs grep -o -m 1 "string" | sort -r)"

Find should search for some files with the same name in folder xyz. Pipe them to grep to search these files for every first matching string in it. Then sort should sort descending.

This works pretty well except of no matter what I try sort will always sort by the filenames but it should sort by the matching strings grep has found. This is what the output looks like

/file3:111
/file2:666
/file1:333

And this is what I wanted echo to display no matter what the filename is:

 /file2:666
 /file1:333
 /file3:111

With grep -h I get the result I want but I also need the filenames to be displayed as additional info.

Score:3
cn flag

You need to tell sort which part of its input you want to sort after. That's what the switch -k (for "key") is for. Let's say you have a list like

/file3 111
/file2 666
/file1 333

You want to sort after the second field, so you need -k 2:

sort -r -k 2

By default, sort separates the fields by a "non-blank to blank transition", or between every non-whitespace character which is followed by a whitespace character. In your case, you separate the fields of your input with a :. So have to tell sort that as well, with the switch -t:

sort -r -k 2 -t ':'

As a more general remark, in a pipeline (multiple commands chained together with |), a later command doesn't know how its input came to be. So thinking about it like "sort needs to look at what came from grep and not from find" is probably not that helpful ;) sort only knows what its input looks like, not who played what part in the construction of the input.

diggidre avatar
br flag
thx @Henning Kockerbeck I already tried with -k but the -t ':' does the trick!
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.