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

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

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

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

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

答え2

awkを使えば十分です。

awk ' { print NR". " $1 } ' < file.txt

$ 1は入力のテキスト文字列、NRは現在の行番号(レコード数など)を追跡する内部awk変数です。

8つの強力なawk組み込み変数 – FS、OFS、RS、ORS、NR、NF、FILENAME、FNR

答え3

nlを使用することもできます。

nl -s. -ba file
     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

関連情報