我有一个 JSON 文件,如下所示:
{
...
"python.pythonPath": "",
"python.defaultInterpreterPath": "",
...
}
我想将其更新为
{
...
"python.pythonPath": "/Users/user/.local/share/virtualenvs/venv-Qxxxxxx9/bin/python",
"python.defaultInterpreterPath": "/Users/user/.local/share/virtualenvs/venv-Qxxxxxx9/bin/python",
...
}
我对使用转义字符感到困惑/以及单引号和双引号。我如何使用 sed 来做到这一点?
供参考。我正在使用 macOS 我尝试过:
sed -i "" 's|/"/"|/"/Users/user//.local/share/virtualenvs/venv-Qxxxxxx9/bin/python/"' settings.json
答案1
这应该与您已经尝试过的方法类似,但不建议以这种方式编辑 json 文件,最好jq
按照已经建议的方式使用。
sed -i 's/""/"\/Users\/user\/.local\/share\/virtualenvs\/venv-Qxxxxxx9\/bin\/python"/g' settings.json
输出应如下所示;
{
...
"python.pythonPath": "/Users/user/.local/share/virtualenvs/venv-Qxxxxxx9/bin/python",
"python.defaultInterpreterPath": "/Users/user/.local/share/virtualenvs/venv-Qxxxxxx9/bin/python".
...
}
答案2
我无法让 sed 命令工作。然而,我找到了一种在 bash 中运行 Python 脚本的方法,它为我完成了这项工作。如果有人有兴趣:
export new_path="/Users/user/.local/share/virtualenvs/venv-Qxxxxx9/bin/python"
python3 - << EOF
import json
import os
with open('settings.json', mode='r+') as file:
data = json.load(file)
data['python.defaultInterpreterPath'] = os.environ['new_path']
data['python.pythonPath'] = os.environ['new_path']
file.seek(0)
json.dump(data, file, indent=4, sort_keys=True)
file.truncate()
EOF
echo 'continue bash'
答案3
我会这样做awk
,这样可以更容易地仅在值为""
和关键是两个所需的之一:
$ awk -F: -vOFS=" : " '
$1=="\"python.pythonPath\"" ||
$1=="\"python.defaultInterpreterPath\""{
$2="\"/Users/user/.local/share/virtualenvs/venv-Qxxxxx9/bin/python\","}
1;
' file
{
...
"python.pythonPath" "/Users/user/.local/share/virtualenvs/venv-Qxxxxx9/bin/python"
"python.defaultInterpreterPath" "/Users/user/.local/share/virtualenvs/venv-Qxxxxx9/bin/python"
...
}