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

求Linux下sed命令:替换.env中指定DB_USERNAME类变量值为root

Solution Using Sed for .env File Modification

Got it, let's solve this specific problem where you need to update only the .env variables that start with DB and end with _USERNAME, setting their values to root—leaving all other variables untouched.

The Sed Command

Here's the exact command you can run in your Linux environment:

sed -i 's/^\(DB.*_USERNAME\)=.*/\1=root/' .env

Breakdown of the Command

Let's break down what each part does so you understand why it works:

  • -i: This flag tells sed to edit the .env file in-place (no need to redirect output to a new file; it modifies the original directly).
  • ^\(DB.*_USERNAME\): The ^ anchors the match to the start of the line. The parentheses \( ... \) capture the variable name (anything starting with DB and ending with _USERNAME) so we can reuse it later.
  • =.*: Matches the equal sign followed by any existing value (the .* means zero or more of any character).
  • \1=root: \1 refers to the captured variable name from earlier, so we keep the original variable name and set its value to root.

Example Before/After

If your .env had these lines:

DB_USERNAME=my_old_user
DB_ABC_DEF_USERNAME=another_user
DB_HOST=127.0.0.1
API_KEY=xyz123

After running the command, it will look like this:

DB_USERNAME=root
DB_ABC_DEF_USERNAME=root
DB_HOST=127.0.0.1
API_KEY=xyz123

Note for macOS Users

If you're on macOS (which uses BSD sed instead of GNU sed), you need to add an empty string after -i to avoid creating a backup file by default:

sed -i '' 's/^\(DB.*_USERNAME\)=.*/\1=root/' .env

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:09:03