Bash:按内容对“查找”中的文件进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18158365/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 06:12:08  来源:igfitidea点击:

Bash: Sort files from 'find' by contents

bashshellsortingfindpiping

提问by false_azure

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 sortto be sorted alphabetically. I've tried piping the output of the above line directly into sortbut this results in the file names being sorted rather than their contents. Do I need to turn the output of findinto an array and then have it processed by sort?

我想提取返回的所有文件的内容(应该是文本)并将其通过管道sort按字母顺序排序。我已经尝试将上述行的输出直接输入管道,sort但这会导致对文件名进行排序而不是对它们的内容进行排序。我是否需要将 的输出find转换为数组,然后由 处理sort

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

[编辑] 我想要的输出是排序后的内容。

回答by Eugen Constantin Dinca

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
  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

回答by Bryan

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.txtand the sorted output will be printed to the terminal window.

否则就去掉,> sorted.txt排序后的输出将打印到终端窗口。