Shell脚本中sed命令里@符号及@$VAR写法的作用是什么?
Hey there! Let's break down that tricky-looking sed command from your dotfiles so it all clicks. First, let's restate the command clearly:
sed "s@$KEY=.*@$KEY=\"$VALUE\"@" -i "$FILE"
1. The @ Symbol as a Sed Delimiter
By default, sed's substitute command uses / as the separator, like s/old/new/. But here's the problem: if your old or new text contains / (super common in paths, environment variables, etc.), you'd have to escape every / with a backslash (\/), which gets messy fast.
Sed lets you swap out the separator for almost any character—@, #, |, even !—as long as you use the same character at the start, between the pattern/replacement, and at the end.
In this command, using @ avoids having to escape any / characters that might be in $KEY or $VALUE. For example, if $KEY was PATH and $VALUE was /usr/local/bin:/usr/bin, using / as the separator would require writing:
sed "s/PATH=.*/PATH=\"\/usr\/local\/bin:\/usr\/bin\"/" -i "$FILE"
...which is way harder to read and maintain. Using @ cleans that up completely.
2. The " @$KEY " Misconception
You mentioned confusion about @$KEY—but that's not a single syntax! The @ here is just the end of the first part of the substitute command, and $KEY is a shell variable that gets expanded before sed runs. Let's split the substitute command into pieces to see:
s@: Starts the substitute command, declaring@as the separator$KEY=.*: The pattern to match. The shell replaces$KEYwith its value first, so if$KEYisUSER, this becomesUSER=.*—which matches any line starting withUSER=followed by any characters (.) any number of times (*)@: Separates the match pattern from the replacement text$KEY=\"$VALUE\": The replacement text. Again, the shell expands$KEYand$VALUEfirst, and escapes the double quotes (\") so they get passed to sed properly. If$KEYisUSERand$VALUEisjane, this becomesUSER="jane"@: Ends the substitute command
3. What the Whole Command Does
Putting it all together: this command searches the file $FILE for any line that starts with $KEY= followed by anything, replaces that entire line with $KEY="$VALUE", and saves the changes directly to the file (that's what -i does—"in-place" editing).
Example
Suppose $FILE has this line:
USER=john_doe
If $KEY=USER and $VALUE=jane_smith, the command will change that line to:
USER="jane_smith"
内容的提问来源于stack exchange,提问作者Holene

