Moshe
Moshe

Reputation: 5149

special printing with awk

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
  1. What is the way I can stay only with the branch name? (I don't care about a "git" solution, I want to know how to achieve that with awk)
  2. 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

Answers (5)

Vampire
Vampire

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

sjsam
sjsam

Reputation: 21965

git branch -r | awk -F/ '{sub(/[[:space:]]*->.*$/,"")}{print $NF}'

should do it.

Output

Dev
HEAD
master

Upvotes: 0

cn0047
cn0047

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

Tom Fenech
Tom Fenech

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

karakfa
karakfa

Reputation: 67507

 ... | awk -F' +|/' -v ORS=, '{if($3!="HEAD") print $3}'

Upvotes: 1

Related Questions