使用SED替换TXT文件中STACK与PORT为环境变量值失败求助
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 withSTACK=(avoids matching random text with "STACK" in it)cut -d'=' -f2splits the line at the=and takes everything after it (your actual value)sed -i.bakedits the file in-place, creating a backup (likeapp_settings.txt.bak)—remove.bakif you don't need a backups/^STACK=.*/STACK=$STACK_VAL/replaces the entire line starting withSTACK=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

