使用 sed over ssh 将项目添加到列表 [英] Using sed over ssh to add item to list
问题描述
我需要修改远程服务器上的 Python 文件,但在 ssh 中格式化 sed 命令时遇到困难.
I need to modify a Python file on a remote server, and I'm stuck formatting a sed command inside an ssh.
要修改的文件有这一行
my_list = [item1"]
我需要更改它以包含另一个项目:
and I need to change it to include another item:
my_list = [item1", item2"]
这是我所拥有的:
ssh user@host 'sed -i \'s/my_list = \[\\"item1\\"]/my_list = \[\\"item1\\", \\";item2\\"]/\' path/to/file'
引号和左括号所需的转义次数让我感到厌烦,因为它在 ssh 中.如果有人可以提供帮助,我将不胜感激!
The number of escapes required for quotes and open brackets is throwing me off since it's within an ssh. I'd appreciate a hand if anyone can help!
推荐答案
不能嵌套单引号,也不能在单引号内转义单引号.到目前为止,在这种特殊情况下,最简单的解决方案是少引用;sed
或 -i
中没有任何内容需要引用.但是因为你的本地shell和远程shell都在处理命令行,所以你需要两层引用.
You can't nest single quotes, and you can't escape single quotes inside single quotes. The simplest solution by far in this particular case is to just quote less; there is nothing in sed
or -i
which requires quoting. But because both your local shell and the remote shell processes the command line, you need two layers of quoting.
ssh user@host sed -i "'s/my_list = \\[\"item1\"]/my_list = [\"item1\", \"item2\"]/'" path/to/file
也许还注意到替换字符串只是一个字符串,所以不需要在那里转义 [
.
Perhaps notice also that the replacement string is just a string, so there is no need to escape the [
there.
要调试这些东西,请尝试
For debugging these things, try
ssh user@host printf '%s\\n' sed -i "'s/my_list = \\[\"item1\"]/my_list = [\"item1\", \"item2\"]/'" path/to/file
在远程主机上看到命令行被分成每行一个标记.
to see the command line split up into one token per line on the remote host.
从根本上说,您可能应该更改远程 Python 脚本,以使用标准格式(如 JSON 或 YAML)读取其输入.编写程序的程序是一种强大的工具,但修改现有程序的简单程序通常会变得脆弱且难以调试.
Fundamentally, you should probably change the remote Python script to read its input in a standard format like JSON or YAML. Programs which write programs are a powerful tool, but unsophisticated programs which modify existing programs are often going to end up brittle and hard to debug.
这篇关于使用 sed over ssh 将项目添加到列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!