Reputation: 5149
I want to print my git branches using awk, and I want only the branch name, without the origin and without knowing what is my working copy.
I came up with git branch -r | awk -F' ' '{print $1}'
but the result looks like this:
origin/Dev
origin/HEAD
origin/master
So I tried git branch -r | awk -F'/' '{print $2}'
and the result was:
Dev
HEAD -> origin
master
How can I replace in the same line the line breaks with comma? For example my goal is to see it like this:
Dev,HEAD,master
Thanks.
Upvotes: 0
Views: 491
Reputation: 38724
This will print out the desired result, the comma separated string
git branch -r | awk '
BEGIN { firstBranch = 1 }
# split branch off from remote
{ branch = substr($1, index($1, "/") + 1) }
# eliminate HEAD reference
branch == "HEAD" { next }
# output comma between branches
!firstBranch { printf "," }
firstBranch { firstBranch = 0 }
# output branch name
{ printf branch }
# final linebreak
END { print "" }
'
or as one-liner without comments
git branch -r | awk 'BEGIN { firstBranch = 1 } { branch = substr($1, index($1, "/") + 1) } branch == "HEAD" { next } !firstBranch { printf "," } firstBranch { firstBranch = 0 } { printf branch } END { print "" }'
Upvotes: 1
Reputation: 21965
git branch -r | awk -F/ '{sub(/[[:space:]]*->.*$/,"")}{print $NF}'
should do it.
Output
Dev
HEAD
master
Upvotes: 0
Reputation: 17091
Here my example:
git branch|awk '{print ($1=="*" ? $2 : $1)}'|awk 'ORS=NR?",":"\n"'
git branch
- prints branches,
awk '{print ($1=="*" ? $2 : $1)}'
- prints name, not *
before current branch,
awk 'ORS=NR?",":"\n"'
- replace \n
with ,
.
My result is:
ZIIPR-1247,ZIIPR-Config,develop,master,stage
Hope it is most simplest example...
Upvotes: 0
Reputation: 74685
This ought to do it:
awk -v OFS="," '{ n = split($1, a, /\//); branches[++b] = a[n] }
END { for (i = 1; i <= b; ++i) printf "%s%s", branches[i], (i<b?OFS:ORS) }'
This gets the last part of each local branch (it assumes that your local branches don't have /
in their names). It stores each name in an array and then prints them out, separated by a comma (using OFS
) and followed by a newline (using ORS
).
It would be easy to add a conditional if (a[n] != "HEAD")
before adding the branch to the array.
Upvotes: 0