1

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?

0

2 Answers 2

4

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)
Sign up to request clarification or add additional context in comments.

4 Comments

I'm experimenting now, for some reason "${arr[0]}" shows the whole contents, while "${arr[1]}" shows none
Please check your awk and bash versions. It requires gnu-awk and bash 4+
Is there a way to do the same thing, but read from a string variable instead of a file? -
Yes sure, just replace awk -v RS='\nM [^\n]+\n' '{ORS = RT "\0"} 1' file with awk -v RS='\nM [^\n]+\n' '{ORS = RT "\0"} 1' <<< "$string"
2

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.