Bash: Sort files from 'find' by contents
Asked Answered
B

2

7

I have the line:

find -maxdepth 1 -type f -iname '*key*'  -not -name '*~'

I want to extract the contents (which should be text) of all the files returned and pipe that into sort to be sorted alphabetically. I've tried piping the output of the above line directly into sort but this results in the file names being sorted rather than their contents. Do I need to turn the output of find into an array and then have it processed by sort?

[edit] The output I want is the sorted contents.

Brian answered 10/8, 2013 at 3:25 Comment(1)
Pipe it through xargs cat then through sort.Champion
C
10

For completeness sake here are a few more ways of doing that:

  1. find -maxdepth 1 -type f -iname '*key*' -not -name '*~' -exec cat {} \; | sort
  2. find -maxdepth 1 -type f -iname '*key*' -not -name '*~' | xargs cat | sort
  3. cat $(find -maxdepth 1 -type f -iname '*key*' -not -name '*~') | sort
Champion answered 10/8, 2013 at 4:8 Comment(0)
C
0

If you would like to save the sorted output into a file, try:

find -maxdepth 1 -type f -iname '*key*'  -not -name '*~' | cat | sort > sorted.txt

otherwise just get rid of > sorted.txt and the sorted output will be printed to the terminal window.

Charged answered 10/8, 2013 at 3:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.