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

Azure Pipeline中如何将文本文件全部内容存入变量?

问题

我有一个greetings.txt文件,内容包含多行数据,尝试在Azure Pipeline的azure-pipeline.yml中将该文件的全部内容存入GREETINGS_CONTENT变量,但目前仅能获取文件的第一行内容。

文件greetings.txt内容:

- hello: 123 
- hello: 456
- hello: 789 

当前azure-pipeline.yml配置:

variables:
- name: MY_TEXT_FILE
  value: 'greetings.txt'
  readonly: true

# Save text file in this variable
- name: GREETINGS_CONTENT
  value: ''

steps:
  - task: Bash@3
    displayName: 'Save text file content in a variable'
    inputs:
      targetType: 'inline'
      script: |
        echo "##vso[task.setvariable variable=GREETINGS_CONTENT]$(cat $MY_TEXT_FILE)"

  - task: Bash@3
    displayName: 'Another task'
    inputs:
      targetType: inline
      script: |
        # This is only printing the first line of the txt file
        # I want to save ALL the txt file content in the variable
        echo "My greetings are: $GREETINGS_CONTENT"

执行Another task后的实际结果仅输出第一行:

- hello: 123

期望输出文件全部内容:

- hello: 123 
- hello: 456
- hello: 789

请问需要修改哪些配置才能达到预期效果?

解决方案

问题根源是##vso[task.setvariable]命令会把换行符识别为命令结束标记,导致只有第一行内容被存入变量。需要对文件内容做转义处理,将换行符替换为Azure Pipeline能识别的%0A转义符。

修改后的配置

variables:
- name: MY_TEXT_FILE
  value: 'greetings.txt'
  readonly: true

# Save text file in this variable
- name: GREETINGS_CONTENT
  value: ''

steps:
  - task: Bash@3
    displayName: 'Save text file content in a variable'
    inputs:
      targetType: 'inline'
      script: |
        # 将换行符替换为Azure Pipeline识别的%0A转义符,同时移除末尾多余的转义符
        CONTENT=$(cat "$MY_TEXT_FILE" | sed -z 's/\n/%0A/g' | sed 's/%0A$//')
        echo "##vso[task.setvariable variable=GREETINGS_CONTENT]$CONTENT"

  - task: Bash@3
    displayName: 'Another task'
    inputs:
      targetType: inline
      script: |
        echo "My greetings are: $GREETINGS_CONTENT"

关键说明

  • sed -z 's/\n/%0A/g':用-z参数让sed以空字符作为行分隔符,确保能捕获所有换行符并替换为%0A
  • sed 's/%0A$//':移除内容末尾多余的%0A,避免变量最后多出空行
  • Azure Pipeline在解析变量时,会自动将%0A转换回换行符,后续任务就能完整输出所有行内容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 01:10:09