gpt4 book ai didi

linux - 在 Shell 中,如果在字符串中找不到,如何插入子字符串

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:50:24 25 4
gpt4 key购买 nike

我希望 changes_summary 的格式始终为 <x> files changed, <y> insertion(+), <z> deletions(-)其中 <x> <y><z>是一些数字,但如果 <y>,diffstat 会遗漏插入和/或删除部分和/或 <z>为零,我试图将其打印为 <x> files changed 0 insertion(+), 0 deletions(-)总是,有没有更好或更简单的方法来做到这一点?我想更改 $changes_summary 变量,以便我可以在脚本的后面部分使用它。

changes_summary=`diff -ur ./dir1 ./dir2 | diffstat | tail -1`
if ! echo $changes_summary | grep -q "insertions" && ! echo $changes_summary | grep -q "deletions" ; then
echo $changes_summary | awk '{print $1 " " $2 " " $3 " " "0 insertion(+)," " " "0 deletions(-)"}'
elif ! echo $changes_summary | grep -q "insertions" && echo $changes_summary | grep -q "deletions" ; then
echo $changes_summary | awk '{print $1 " " $2 " " $3 " " "0 insertion(+), "$4 " " $5 }'
elif echo $changes_summary | grep -q "insertions" && ! echo $changes_summary | grep -q "deletions" ; then
echo $changes_summary | awk '{print $1 " " $2 " " $3 " " $4 " " $5 "0 deletions(-)" }'

最佳答案

如果没有一些严肃的 bash 魔术或其他语言,您可以获得的最接近的可能是如下所示。

changes_summary=`diff -ur ./dir1 ./dir2 | diffstat -s`
CC=$(echo "$changes_summary" | sed -n 's:\(.*[0-9]\+ .* changed\).*:\1:p')
II=$(echo "$changes_summary" | sed -n 's:.*\([0-9]\+ insertions\?\).*:\1:p')
DD=$(echo "$changes_summary" | sed -n 's:.*\([0-9]\+ deletions\?\).*:\1:p')
echo "${CC}, ${II:-0 insertions}(+), ${DD:-0 deletions}(-)"

Sed 去除了与每个统计信息相对应的消息。 -n 抑制正常输出,p 仅在找到匹配项时打印。如果不是,则 CC、II、DD 将为空,在这种情况下,${II:-...} 模式将替换默认值。

来自 man bash:

${parameter:-word} Use Default Values. If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.

请注意,将 (s) 与 s\? 一起保留对您来说可能有点矫枉过正。

另一种选择是,在 bash 中,您可以使用 [[ $a =~ "b"]] 检查容器并使用您原来的方法。它至少让你省去了 greps,如果你去掉引号,这里的 "b" 也可以是正则表达式。

if ! [[ "$changes_summary" =~ "insert" ]]; then
awk ...
fi

您还可以在 man bash 中找到 =~

关于linux - 在 Shell 中,如果在字符串中找不到,如何插入子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32107242/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com