Searching git diff output for specific kinds of changes

Question

I am writing a Korn Shell script, where I am trying to iterate over specific lines in the git diff result of a file. For those who don't know, git diff lists the changes made to a file, and its output would look something like this (assuming only lines 3 and 5 changed):

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 

I have stored this result in a string variable (say, diff), and I need to iterate over each line in diff beginning with a + or a - (for instance, - previous version of line 3). The most intuitive solution is obviously to iterate over each line in diff and use something like if line contains + or -, but I can't do this since diff is not an array of separate lines, but a string separated by \n at places.

So what I end up looking for is a way to extract each part of the string between two \n characters.

How do I achieve this in Korn shell? Or maybe you guys could suggest better alternatives.


Show source
| git   | shell   | ksh   2017-11-29 20:11 1 Answers

Answers to Searching git diff output for specific kinds of changes ( 1 )

  1. 2017-11-29 20:11

    Below approach should fit

    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
    

    Since you need lines starting with either + or - I have added a grep too to filter lines.


    Note: used ksh 93u+ 2012-08-01 emulator found [ here ]

Leave a reply to - Searching git diff output for specific kinds of changes

◀ Go back