如何使用 sed 命令更改特定行中单词的替换?

sur*_*bhi 4 sed text-processing

我必须在第 4 行更改一个单词,所以我使用了这个命令:

sed -i '4 s/previous_word/new_word/' filename
Run Code Online (Sandbox Code Playgroud)

它工作得很好。但是,如果我将行号保存在变量中并尝试相同的命令,则会出现此错误:

$ sed -i '${line_no} s/previous_word/new_word/' filename
 error
 sed: -e expression #1, char 5: expected newer version of sed
Run Code Online (Sandbox Code Playgroud)

我怎样才能正确地做到这一点?

Jos*_* R. 6

使用双引号代替单引号。

sed -i "${line_no}..."
Run Code Online (Sandbox Code Playgroud)

请参阅堆栈溢出:bash 中单引号和双引号的区别

  • 更好的是:`sed -i "${line_no}"'s/previous_word/new_word/' filename` - 这避免了可能由指令行其余部分的 shell 扩展引起的问题 (4认同)