面试题答案
一键面试#!/bin/bash
# 定义颜色数组
colors=("31" "32" "33" "34" "35" "36")
color_index=0
# 分割文件内容为代码段
IFS='###' read -ra code_segments < file.txt
for segment in "${code_segments[@]}"; do
# 跳过空的代码段
if [[ -z "$segment" ]]; then continue; fi
# 使用nl命令添加行号
numbered_segment=$(echo "$segment" | nl -b a -n rz)
# 计算代码段行数
line_count=$(echo "$numbered_segment" | wc -l)
# 添加注释记录行数
numbered_segment="$numbered_segment\n# Lines in this segment: $line_count"
# 以彩色显示
color_code="${colors[color_index]}"
echo -e "\e[${color_code}m$numbered_segment\e[0m"
# 切换颜色
color_index=$(( (color_index + 1) % ${#colors[@]} ))
done
- 颜色定义:定义一个颜色数组
colors
,包含多种颜色代码,color_index
用于追踪当前使用的颜色。 - 分割代码段:使用
IFS='###'
设置分隔符为###
,并通过read -ra
将文件内容读取到数组code_segments
中。 - 处理每个代码段:
- 跳过空的代码段。
- 使用
nl -b a -n rz
命令为代码段添加行号,-b a
表示对所有行编号,-n rz
表示行号格式为三位数字,不足三位前面补零。 - 计算代码段行数,并添加注释记录行数。
- 根据
color_index
从颜色数组中获取颜色代码,以彩色显示代码段,最后重置颜色。 - 切换到下一个颜色。
假设代码文件名为file.txt
,将上述脚本保存为一个可执行文件,运行该脚本即可完成任务。