たとえば、/usr/libディレクトリにある最大5つのファイルをどのようにリストしますか?

たとえば、/usr/libディレクトリにある最大5つのファイルをどのようにリストしますか?

/usr/libたとえば、ディレクトリ内の最大5つのファイルをどのようにリストしますか?

また、使用している各コードの簡単な説明を追加してください。

ベストアンサー1

最も簡単な方法は、サイズでソートして最後の5行を印刷することです。

ls -Sr /usr/lib | tail -n 5

からman ls

   -r, --reverse
          reverse order while sorting
   -S     sort by file size

tailファイルの最後のN行だけを印刷します。

   -n, --lines=K
          output the last K lines, instead of the last 10; or use -n +K to
          output lines starting with the Kth

サブディレクトリのファイルも確認するには、次の手順を実行します。

find /usr/lib -type f -ls | sort -gk7 | tail -n 5

このfindコマンドは次のファイルを探しますman find

   -type c
          File is of type c:
          [ ... ]
          f      regular file
   -ls    True;  list  current file in ls -dils format on standard output.
          The block counts are of 1K blocks, unless the environment  vari‐
          able  POSIXLY_CORRECT  is set, in which case 512-byte blocks are
          used.  See the UNUSUAL FILENAMES section for  information  about
          how unusual characters in filenames are handled.

sort期待どおりに入力がソートされます。からman sort

   -g, --general-numeric-sort
          compare according to general numerical value
   -k, --key=KEYDEF
          sort via a key; KEYDEF gives location and type

したがって、-g数値順に並べ替え、-k77番目のフィールドに並べ替えます。この場合はfind -lsファイルサイズです。

これは比較的強力である必要があり、スペースや奇妙な文字を含むファイル名には問題ありません。とにかく、検索しているので、/usr/lib奇妙なファイル名が出る可能性はほとんどありません。

おすすめ記事