生成 100 行数据到文件 file.txt
for ((i=1; i<=100; i++));do
if [ ${i} -lt 10 ];then
num=$(( (RANDOM % 5) + 10 + i ))
else
num=$(( (RANDOM % 5) + 10 + 15 ))
fi
echo ${num}
done
通过文件 file.txt 生成折线图
#!/bin/bash
# 指定文件名,该文件必须为数字
file='./file.txt'
# 指定折线图的符号
symbol='@'
# 指定x轴最大长度
x_length=150
# 指定y轴高度
y_length=25
# 生成文件时需要的临时文件(不用配置)
tmp_file='./.tmp.txt'
new_file='./.new.txt'
# 读取文件行数,如果为0则退出,如果小于x轴长度则更新x轴长度,如果大于x轴长度则按比例只取指定的长度
file_rows=$(wc -l < ${file})
if [ ${file_rows} -eq 0 ];then
echo -e "[ERROR] If the file is empty, exit !"
exit 1
elif [ ${file_rows} -le ${x_length} ];then
x_length=${file_rows}
else
residue=$((file_rows / x_length))
awk "NR % ${residue} == 0" ${file} > ${new_file}
file=${new_file}
fi
# 获取最大值、最小值
max_number=$(awk 'NR==1 {max=$1} $1>max {max=$1} END{print max}' ${file})
min_number=$(awk 'NR==1 {min=$1} $1<min {min=$1} END {print min}' ${file})
# 获取最大行的字符数
max_char=$(awk 'NR==1 {max=length} length>max {max=length} END{print max}' ${file})
# 如果最大行的字符数为偶数,将第1列字符数+3,(为了避免对不齐的问题),+4是为了避免存在负数对不齐问题
[ $((max_char % 2)) -eq 0 ] && max_char=$((max_char + 3)) || max_char=$((max_char + 4))
x_symbol_length=$((x_length + max_char + 3))
# 输出第一行图表横线字符
perl -E "say '—' x ${x_symbol_length}" >${tmp_file}
# 输出第一行说明
title="scatter plot"
padding=$[(${x_length} - ${#title}) / 2]
printf "|%-${max_char}s|%-${padding}s%s%-${padding}s|\n" "unit" "" "${title}" "" >>${tmp_file}
perl -E "say '—' x ${x_symbol_length}" >>${tmp_file}
# 按指定文件的数字输出单位长度
num=${max_number}
scale=$(awk "BEGIN{print int( (${max_number} - ${min_number}) / ${y_length} + 1)}")
for ((i=1; i<=y_length; i++));do
printf "|%-${max_char}s|\n" "${num}" >>${tmp_file}
num=$(awk "BEGIN{print int(${num} - ${scale})}")
done
# 横向刻划散点图
x_length=$((x_length + 1))
for ((i=1; i<=x_length; i++));do
num=${max_number}
for ((j=1; j<=y_length; j++));do
file_row=$((j+3))
file_num=$(sed -n "${i}p" ${file} |awk "{print int(\$1 / ${num})}")
if [[ ${i} == ${x_length} ]];then
sed_symbol='|'
result=0
elif [[ ${file_num} == 1 ]];then
sed_symbol="${symbol}"
result=1
else
sed_symbol=' '
result=0
fi
sed -i "${file_row}s/\$/${sed_symbol}/" ${tmp_file}
if [[ ${result} == 1 ]];then
if [[ ${j} == ${y_length} ]];then
continue 2
else
sed_str="$((file_row+1)),$((y_length+3))"
sed -i "${sed_str}s/\$/ /" ${tmp_file}
continue 2
fi
fi
num=$(awk "BEGIN{print int(${num} - ${scale})}")
done
done
# 输出最后一行图表横线字符
perl -E "say '—' x ${x_symbol_length}" >>${tmp_file}
cat ${tmp_file}
[ -f ${tmp_file} ] && rm -rf ${tmp_file}
[ -f ${new_file} ] && rm -rf ${new_file}