MST

星途 面试题库

面试题:Bash脚本中复杂文本格式化及分页打印

编写一个Bash脚本,从一个文本文件读取内容,将每一行文本按照固定宽度进行格式化(例如每行80个字符),并且实现分页打印功能,当一页内容满(假设一页为24行)时暂停,等待用户按键继续。解释实现过程中涉及到的文本处理和控制逻辑。
11.7万 热度难度
编程语言Bash

知识考点

AI 面试

面试题答案

一键面试

以下是实现该功能的Bash脚本:

#!/bin/bash

# 检查文件是否提供
if [ $# -ne 1 ]; then
    echo "Usage: $0 <filename>"
    exit 1
fi

filename=$1
line_width=80
lines_per_page=24
current_line=0

while read -r line; do
    # 格式化每行文本为固定宽度
    formatted_line=$(printf "%-${line_width}.${line_width}s" "$line")
    echo "$formatted_line"
    current_line=$((current_line + 1))

    # 检查是否满一页
    if [ $current_line -eq $lines_per_page ]; then
        read -p "Press any key to continue..."
        current_line=0
    fi
done < "$filename"

实现过程解释

  1. 参数检查
    • if [ $# -ne 1 ]; then 检查脚本运行时是否提供了一个文件名参数。如果没有,输出使用提示并退出脚本。
  2. 变量初始化
    • filename=$1 将传入的文件名赋值给 filename 变量。
    • line_width=80 设置每行的固定宽度为80个字符。
    • lines_per_page=24 设置每页的行数为24行。
    • current_line=0 初始化当前行数为0。
  3. 逐行读取与格式化
    • while read -r line; do 逐行读取文件内容,-r 选项防止反斜杠转义。
    • formatted_line=$(printf "%-${line_width}.${line_width}s" "$line") 使用 printf 命令将每行文本格式化为固定宽度。%- 表示左对齐,${line_width} 表示宽度,.${line_width} 表示最大宽度。
    • echo "$formatted_line" 输出格式化后的行。
    • current_line=$((current_line + 1)) 增加当前行数。
  4. 分页控制
    • if [ $current_line -eq $lines_per_page ]; then 检查当前行数是否达到每页的行数。
    • read -p "Press any key to continue..." 如果达到,提示用户按任意键继续,并暂停脚本执行,等待用户输入。
    • current_line=0 重置当前行数,准备下一页的计数。
  5. 文件读取
    • done < "$filename" 从指定的文件中读取内容作为 while 循环的输入。