我需要编写一个程序,从文件中读取行,然后输出这些行。
所以这些文件包含以下内容:
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