在 git 差异输出中搜索特定类型的更改

Searching git diff output for specific kinds of changes

我正在编写一个 Korn Shell 脚本,我试图在其中迭代文件的 git diff 结果中的特定行。对于那些不知道的人,git diff 列出了对文件所做的更改,其输出看起来像这样(假设只更改了第 3 行和第 5 行):

unchanged line 1
unchanged line 2
- previous version of line 3
+ new version of line 3 
unchanged line 4
- previous version of line 5
+ new version of line 5 

我已将此结果存储在一个字符串变量中(例如 diff),我需要遍历 diff 中以 + 或 [= 开头的每一行17=](例如,- previous version of line 3)。最直观的解决方案显然是遍历 diff 中的每一行并使用 if line contains + or - 之类的东西,但我不能这样做,因为 diff 不是单独行的数组,而是一个在某些地方用 \n 分隔的字符串。

所以我最终寻找的是一种提取两个 \n 字符之间的字符串的每个部分的方法。

如何在 Korn shell 中实现这一点?或者你们可以提出更好的选择。

下面的方法应该适合

git diff | grep '^[+-]' |  while read -r -d$'\n' line
do 
if [ ! -z "$line" ] 
# The last line would always be empty, but cond. above is an overkill anyway
then
 # Do something useful with "$line"
fi    
done

因为您需要以 +- 开头的行,所以我也添加了 grep 来过滤行。


注意: 使用了 ksh 93u+ 2012-08-01 找到了模拟器 [ here ]