[英]Practice Linux Shell Scripting
我的家庭作业是写一个shell脚本来读取一个“log.txt”并逐行显示其注释。 每行都应以其行号作为前缀。
我到目前为止的脚本:
path="/home/user/log.txt"
while i=read -r line
do
echo "$line"
done < "$log_file"
输入文件:
How are you
Where are you
预期输出:
1. How are you
2. Where are you
考虑添加一个计数器,在每一行上增加一个计数器,然后在每一行打印计数器。
还要注意设置 log_file 的修复,更新为读取命令。
log_file="/home/user/log.txt"
line_no=0
while read -r line
do
line_no=$((line_no+1))
printf "%d. %s\n" $line_no "$line"
done < "$log_file"
要考虑的一种替代方法是调用执行确切任务的nl
实用程序。
在python 3.8中这有效
count = 0 with open("log.txt") as file_in: lines = [] for line in file_in: lines.append(line) print('{} {}'.format(count, line)) count +=1
不是shellscript,而是一些实用程序/程序可以做到这一点。
grep -n . logfile.txt
cat -n logfile.txt
awk '{print NR" "$0}' logfile.txt
还有很多...
这是一个使用 bash 的方法。
#!/usr/bin/env bash
n=0
while IFS= read -r line; do
printf '%d. %s\n' "$n" "$line"
((n++))
done < logfile.txt
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.