Slava.In
Slava.In

Reputation: 1059

How to split git log output into an array of commits in bash?

I'm not good at bash, and what I was trying to do is to get information from git log --name-status branch_one...branch_two and after that split output by commits, for example:

git_command_output="
commit one
Author: Johny
Date: 01/01/1999

feat: add something

M src/some_file.txt

commit two
Author: Alex
Date: 02/01/1999

fix: bug

M src/some_file.txt"

From the above I would want to create and array of strings, where each string will be information about one commit.

For instance array would look something like that:

echo "${array[0]}" 

# Author: Johny
# Date: 01/01/1999

# feat: add something

# M src/my_file.txt

echo "${array[1]}" 

# Author: Alex
# Date: 02/01/1999

# fix: bug

# M src/foreign_file.txt

What I tried (didn't work):

array[0]=$(echo "$git_command_output" | awk '{split($0, array, "commit"); print array[0]}')

IFS='commit' read -r -a array <<< "$git_command_output"

Is there a concise way to do it, preferably using awk?

Upvotes: 1

Views: 668

Answers (2)

anubhava
anubhava

Reputation: 785481

You may use this readarray with awk:

IFS= readarray -d '' -t arr < <(awk -v RS='\nM [^\n]+\n' '{ORS = RT "\0"} 1' file)

# check array content
declare -p arr

declare -a arr=([0]=$'commit one\nAuthor: Johny\nDate: 01/01/1999\n\nfeat: add something\n\nM src/some_file.txt\n' [1]=$'\ncommit two\nAuthor: Alex\nDate: 02/01/1999\n\nfix: bug\n\nM src/some_file.txt\n')

Here:

  • We add \0 after each record using awk
  • Then use -d '' to make sure to read \0 delimited text in array arr

Another simpler any-version awk would be:

IFS= readarray -d '' -t arr < <(awk '{printf "%s", $0 (/^M / ? "\0" : ORS)}' file)

Upvotes: 4

1ace
1ace

Reputation: 5288

You can filter the output of many git commands (such as log) to those that affect specific files, simply by adding the paths of these files at the end of the command. Try:

git log --name-status branch_one...branch_two -- src/my_file.txt

Upvotes: 2

Related Questions