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

使用SED替换TXT文件中STACK与PORT为环境变量值失败求助

Fixing Sed Replacement for STACK & PORT Fields Using Env Variables

Got it, let's get that sed replacement working for you! I'll walk through practical, reliable solutions based on typical file setups—just tweak them to match your actual env file and target text file.

First, Let's Define Our Example Files

Let's assume:

  • Your environment variable file (let's call it env_config) looks like this:
    STACK=production-cluster
    PORT=443
    APP_ID=12345
    
  • Your target TXT file (say app_settings.txt) has lines you need to update:
    SERVICE_NAME=my-web-app
    STACK=default-test-stack
    PORT=8080
    LOG_LEVEL=info
    

Solution 1: Read Env Values Directly & Replace

First, we'll extract the STACK and PORT values from your env file, then use sed to swap out the old values in your target file.

Run these commands in your terminal:

# Extract the values from your env file (adjust the filename if yours is different)
STACK_VAL=$(grep '^STACK=' env_config | cut -d'=' -f2)
PORT_VAL=$(grep '^PORT=' env_config | cut -d'=' -f2)

# Replace the lines in your target TXT file (add .bak to keep a backup of the original)
sed -i.bak "s/^STACK=.*/STACK=$STACK_VAL/" app_settings.txt
sed -i.bak "s/^PORT=.*/PORT=$PORT_VAL/" app_settings.txt

What's happening here?

  • grep '^STACK=' ensures we only grab the line that starts exactly with STACK= (avoids matching random text with "STACK" in it)
  • cut -d'=' -f2 splits the line at the = and takes everything after it (your actual value)
  • sed -i.bak edits the file in-place, creating a backup (like app_settings.txt.bak)—remove .bak if you don't need a backup
  • s/^STACK=.*/STACK=$STACK_VAL/ replaces the entire line starting with STACK= with your new value

Solution 2: Load Env Variables Into Your Shell First

If your env file is a standard .env format (no extra comments or weird formatting), you can load it directly into your shell first, then run sed:

# Load all env variables from your .env file
source .env

# Replace the fields in your target file
sed -i.bak "s/^STACK=.*/STACK=$STACK/" app_settings.txt
sed -i.bak "s/^PORT=.*/PORT=$PORT/" app_settings.txt

Handling Special Characters (If Your Values Have /, &, or Spaces)

If your STACK or PORT values include special characters like /, &, or spaces, the standard / delimiter in sed will break things. Just switch to a different delimiter (like # or |):

# Example: If STACK_VAL is "prod/stack-1", use # as the delimiter
sed -i.bak "s#^STACK=.*#STACK=$STACK_VAL#" app_settings.txt

Quick Check to Verify

After running the commands, open your target file to confirm the changes:

cat app_settings.txt

You should see your new STACK and PORT values in place!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 03:57:58