You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在macOS Shell脚本中用AWK变量提取默认打印机描述名

解决macOS Shell脚本中向AWK传递默认打印机变量的问题

问题分析

你的脚本核心问题在于通过字符串拼接向AWK传递$printer_name变量时,可能因变量内容的正则特性(即使当前是下划线,后续若出现.、*等元字符也会出错)导致匹配失效;另外macOS Sonoma切换打印机后出现空输出,大概率是lpstat的系统缓存延迟问题。

修复后的基础版脚本

先修正AWK的变量传递方式,改用-v参数安全传参,避免字符串拼接的潜在问题:

#!/bin/bash
default_printer_info=$(lpstat -d)
printer_name=$(echo "$default_printer_info" | awk '{print $4}')
# 使用-v参数传递变量给AWK,用index做精确字符串匹配
lpstat -l -p | awk -v printer="$printer_name" 'c&&!--c;index($0, printer){c=4}' | grep Description: | cut -d " " -f2-

优化版脚本(减少管道,更高效)

直接用AWK完成所有逻辑,无需额外grep和cut,提升脚本效率:

#!/bin/bash
# 获取默认打印机名称
default_printer=$(lpstat -d | awk '{print $4}')

# 一次性提取友好描述
printer_description=$(lpstat -l -p | awk -v target_printer="$default_printer" '
    # 找到包含目标打印机名的行后,标记后续要提取描述
    index($0, target_printer) > 0 {
        track=1
        next
    }
    # 标记生效后,找到Description行并提取内容
    track && /Description:/ {
        sub(/^.*Description: /, "")  # 移除前缀"Description: "
        print
        exit  # 找到结果后直接退出,避免多余处理
    }
')

# 输出结果
echo "$printer_description"

Sonoma系统兼容优化

针对Sonoma切换打印机后输出为空的问题,改用system_profiler获取打印机信息(系统缓存更稳定):

#!/bin/bash
default_printer=$(lpstat -d | awk '{print $4}')

printer_description=$(system_profiler SPPrintersDataType | awk -v target="$default_printer" '
    index($0, target) > 0 {
        in_target=1
        next
    }
    in_target && /Description:/ {
        sub(/^ *Description: /, "")
        print
        exit
    }
')

echo "$printer_description"

关键说明

  1. 使用awk -v var="$shell_var"是向AWK传递shell变量的标准安全方式,避免字符串拼接导致的正则匹配错误。
  2. 用index($0, target_printer)替代正则匹配$0 ~ target_printer,可以确保是精确字符串匹配,不会因打印机名包含正则元字符(如.、+)而失效。
  3. system_profiler的打印机数据来自系统底层,比lpstat更不易受切换打印机后的缓存影响。

内容的提问来源于stack exchange,提问作者emendelson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 12:05:05