我想对 git log
的输出进行后期处理一直在玩 --pretty
设置。当我例如做
--pretty=format:'{"sha":"%h","message":"%B","author":"%aN <%aE>","commit":"%cE","date":"%cD"}
我得到一些类似 JSON 的输出;当我输入 {
或 }
甚至是 "
进入提交消息,这弄乱了我的输出。
有没有办法告诉git log
转义那些字符,例如通过在前面加上 \
?
有两个类似的问题Git log output to XML, JSON or YAML和 Git log output preferably as XML ,但它们都没有解决特殊字符的转义问题(例如,如果在 XML 情况下我将 <foo>
放入我的提交消息中,生成的 XML 将被破坏)。
最佳答案
转义字符串不是 Git 的工作; git log
没有任何东西可以帮助你做到这一点。要实现您的目标,您需要像 sed
这样的工具来为您编辑字符串。
试试这个(应该在大多数 shell 中工作,但我只检查了 Cygwin bash):
function escape_chars {
sed -r 's/(\{\}")/\\\1/g'
}
function format {
sha=$(git log -n1 --pretty=format:%h $1 | escape_chars)
message=$(git log -n1 --pretty=format:%B $1 | escape_chars)
author=$(git log -n1 --pretty=format:'%aN <%aE>' $1 | escape_chars)
commit=$(git log -n1 --pretty=format:%cE $1 | escape_chars)
date=$(git log -n1 --pretty=format:%cD $1 | escape_chars)
echo "{\"sha\":\"$sha\",\"message\":\"$message\",\"author\":\"$author\",\"commit\":\"$commit\",\"date\":\"$date\"}"
}
for hash in $(git rev-list)
do
format $hash
done
以上将转义{
和}
而不是\
,尽管来自JSON.org \{
和 \}
都是无效转义;只有 \
和 "
需要转义。(将 sed
表达式替换为 sed -r 's/("\\)/\\\1/g'
用于真正的 JSON 输出。)
尽管 %cE
命令实际上给出了提交者的电子邮件地址,但我也保留了您示例中的“提交”值;我不确定这是否是您想要的。
(这现在包括 correct but rejected edit by macrobug 。谢谢!)
关于git - 我可以在 git log 输出中转义字符吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9301673/