求Linux下sed命令:替换.env中指定DB_USERNAME类变量值为root
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.envfile 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 withDBand 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:\1refers to the captured variable name from earlier, so we keep the original variable name and set its value toroot.
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

