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

如何简化提取非bash脚本文件变量的awk命令?

从非Bash配置文件提取变量的简化方案

场景说明

需要提取的配置文件内容示例:

App(
    # Folder name of the application same as application id
    # Only file name appropriate characters, single "word" allowed
    # for appid
    appid="my_app",
    # name of the app
    name="Voltage Calculator",
    apptype=platform.EXTERNAL,
    # (entry point) of the application
    entry_point="my_app_main",
    stack_size=2 * 1024,
    # Application category
    category="Tools",
    requires=["gui"],
    app_icon="icons/my_app.png",
    app_icon_assets="icons",
    # Optional values
    app_version=(1, 0),
    # Short text description of the app, no links or markup/markdown
    # here.
    app_description="App does this cool thing",
    app_author="My name",
    app_weburl="https://github.com/myrepository/",
)

当前使用的提取命令:

filename=~/Programming/myfile.ext
awk -F'appid' '{print $2}' $filename | awk -F'=' '{print $2}' | awk -F'"' '{print $2}' | xargs

问题解答

原写法的可行性

你的原写法完全可行,确实能提取到appid的值,xargs也能有效去除结果周围的空白字符。但多次调用awk+管道的方式比较冗余,没必要拆分这么多步骤。

单个awk命令简化方案

可以用单个awk命令完成提取,同时省去xargs,有两种常用写法:

写法一:正则替换

filename=~/Programming/myfile.ext
awk '/appid/ { gsub(/.*appid="|",.*/, "", $0); print $0 }' "$filename"
  • 逻辑:先匹配包含appid的行,再用gsub把appid="开头的部分和",结尾的部分替换为空,直接输出剩余的目标值。

写法二:多分隔符分割

filename=~/Programming/myfile.ext
awk -F'["=,]' '/appid/ { print $3 }' "$filename"
  • 逻辑:把"、=、,作为字段分隔符,包含appid的行分割后,第3个字段就是需要的my_app。

这两种方式都能直接输出无多余空白的结果,不需要额外调用xargs。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 22:22:46