ファイル内の行番号を含む行を読み取って印刷するプログラムを作成します。

ファイル内の行番号を含む行を読み取って印刷するプログラムを作成します。

ファイルから行を読み取り、その行を出力するプログラムを作成する必要があります。

したがって、これらのファイルには次の内容が含まれます。

This is the first line
This is the second line
This is the third line

This was a blank line

出力は次のようになります。

1. This is the first line
2. This is the second line
3. This is the third line
4.
5. This was a blank line

私は私ができることを知っています:

nl -b a tst16

ただし、数字を追加した後は「.」は印刷されません。ループのような方法があるかどうか疑問に思います。

ベストアンサー1

短いwhile構造を使用してください。

% i=1; while IFS= read -r line; do printf '%s. %s\n' "$i" "$line"; ((i++)); done <file.txt

1. This is the first line
2. This is the second line
3. This is the third line
4. 
5. This was a blank line

拡張:

#!/usr/bin/env bash
i=1
while IFS= read -r line; do 
    printf '%s. %s\n' "$i" "$line"
    ((i++))
done <file.txt

おすすめ記事