数字が前に付けられた現在のディレクトリのファイルのリスト

数字が前に付けられた現在のディレクトリのファイルのリスト

私はbashを学ぶつもりで、次のようにa.shでbashスクリプトを使用してフォルダ内のファイルを一覧表示しようとしています。

1: a.sh
2: b.sh
3: c.sh

lsとfindコマンドを見てみましたが、必要に応じて数字が接頭辞で付いていないようです。助けてください!

ベストアンサー1

これを行う方法はいくつかあります。たとえば、ファイル名に改行文字が含まれていないと確信している場合は、次のようにします。

$ ls | cat -n
     1  a.sh
     2  b.sh
     3  c.sh
     4  d.sh

改行やその他の奇妙な文字を含むファイル名を処理するより安全な方法:

$ c=0; for file in *; do ((c++)); printf '%s : %s\n' "$c" "$file"; done
1 : a.sh
2 : b.sh
3 : c.sh
4 : d.sh

後者の2つがより良い理由を確認するには、改行文字を含むファイル名を作成します。

$ touch 'a long file name'
$ touch 'another long filename, this one has'$'\n''a newline character!'

次に、両方のメソッドの出力を比較してみましょう。

$ ls | cat -n
     1  a long file name
     2  another long filename, this one has
     3  a newline character!
     4  a.sh
     5  b.sh
     6  c.sh
     7  d.sh

上記のように、解析ls(通常は悪い考え)のため、改行のあるファイル名は2つの別々のファイルとして扱われます。正しい出力は次のとおりです。

$ c=0; for file in *; do ((c++)); printf '%s : %s\n' "$c" "$file"; done
1 : a long file name
2 : another long filename, this one has
a newline character!
3 : a.sh
4 : b.sh
5 : c.sh
6 : d.sh

@Vikybossがコメントで指摘したように、上記のシェルソリューションは$cループが終了した後も持続する変数を設定します。これを防ぐには、unset c最後に追加するか、別の方法を使用できます。たとえば、

$ perl -le 'for(0..$#ARGV){print $_+1 ." : $ARGV[$_]"}' *
1 : a long file name
2 : another long filename, this one has
a newline character!
3 : a.sh
4 : b.sh
5 : c.sh
6 : d.sh

おすすめ記事