Score:0

Tail in combination with sort

br flag

I use tail in a variable to echo contents of multiple files in a folder.

VAR="$(tail -n +1 DIR/*/file)"

This outputs all the files contents with the needed filename on top like

==> /folder/subdir1/file <==

some content from file in subdir 1

==> /folder/subdir3/file <==

some content from file in subdir 3

==> /folder/subdir2/file <==

some content from file in subdir 2

Thats fine but when I also want to sort it for subdirs

VAR="$(tail -n +1 DIR/*/file | sort)"

it gets displayed like

some content from file in subdir 1

some content from file in subdir 2

some content from file in subdir 3

==> /folder/subdir1/file <==

==> /folder/subdir2/file <==

==> /folder/subdir3/file <==

How can I achieve it gets displayed sorted but that it looks like without sort command in first example?

hr flag
This sounds like an XY problem - what is your actual end goal? It will likely be easier to sort the files individually (using a shell loop for example) than to unscramble the omelette after they've been concatenated.
cn flag
Ray
What order do you want? Based on the input filenames? Instead of sorting the output of tail, perhaps you can get the list of filenames (i.e., 'DIR/*/file') and sort that first, then run tail?
diggidre avatar
br flag
Hmm I give up with tail in this case. The short info I needed is now extended to the file names so find and sort are good to go for now. Still a bit interested how this could be figured out with tail but I'm still in early stage of learn coding. Sometimes it's ok to go the easy way I think :)
Raffa avatar
jp flag
You could for example format each two consecutive none empty lines to be NULL delimited and pipe the output to `sort -z -t "$'\n'”` then pipe the output to e.g. `tr '\0' '\n'` returning NULL to newline … But, simpler and more efficient solutions might be suggested if you show us the big picture by stating your desired work flow and end goal instead of focusing on your attempted solution.
diggidre avatar
br flag
thx 4 your suggestion @Raffa . Seems fiddly :) For now I will stay with my workaround :)
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.