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

Shell脚本中sed命令里@符号及@$VAR写法的作用是什么?

Understanding That Sed Command in Your Dotfiles Script

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 $KEY with its value first, so if $KEY is USER, this becomes USER=.*—which matches any line starting with USER= 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 $KEY and $VALUE first, and escapes the double quotes (\") so they get passed to sed properly. If $KEY is USER and $VALUE is jane, this becomes USER="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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:42:20