![ファイル内の行番号を含む行を読み取って印刷するプログラムを作成します。](https://linux33.com/image/84985/%E3%83%95%E3%82%A1%E3%82%A4%E3%83%AB%E5%86%85%E3%81%AE%E8%A1%8C%E7%95%AA%E5%8F%B7%E3%82%92%E5%90%AB%E3%82%80%E8%A1%8C%E3%82%92%E8%AA%AD%E3%81%BF%E5%8F%96%E3%81%A3%E3%81%A6%E5%8D%B0%E5%88%B7%E3%81%99%E3%82%8B%E3%83%97%E3%83%AD%E3%82%B0%E3%83%A9%E3%83%A0%E3%82%92%E4%BD%9C%E6%88%90%E3%81%97%E3%81%BE%E3%81%99%E3%80%82.png)
ファイルから行を読み取り、その行を出力するプログラムを作成する必要があります。
したがって、これらのファイルには次の内容が含まれます。
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変数です。
答え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