Search code examples
gitshellsedcommand-substitution

Extracting parts of whitespace seperated string


If have several Git repositories containing a file mergedriver.info

This file looks always like this:

<project name>
<repository name>

A script, triggered by a Git merge driver, is evaluating this file:

mergedriverinfo="$(git cat-file -p HEAD:mergedriver.info)"
success=$?
if [[ "$success" == "0" ]]; then
    log "Evaluating mergedriver.info"

    PROJECT_KEY="$(sed -E 's/([^\s]+)\s+([^\s]+)/\1/' <<< $mergedriverinfo)"
    REPO_SLUG="$(sed -E 's/([^\s]+)\s+([^\s]+)/\2/' <<< $mergedriverinfo)"

    log "PROJECT_KEY=$PROJECT_KEY"
    log "REPO_SLUG=$REPO_SLUG"
else
    log "Unable to read mergedriver.info"
    exit 1
fi

I don't understand the behaviour of sed in this case.

For this mergedriver.info:

test
conflict-on-auto-merge

The log output looks like this:

2017-07-20 11:05:51.747 PROJECT_KEY=test
2017-07-20 11:05:51.748 REPO_SLUG=tesconflict-on-auto-merge

At first I tried reading the mergedriver.info with sed -n 1p/2p and head/tail -1, but unfortunately the output of $(git cat-file -p HEAD:mergedriver.info) is different for two different platforms on which this script is running:

Platform 1:

$ od -c <<< $(git cat-file -p HEAD:mergedriver.info)
0000000   t   e   s   t  \n   c   o   n   f   l   i   c   t   -   o   n
0000020   -   a   u   t   o   -   m   e   r   g   e  \n
0000034

Platform 2:

±  od -c <<< $(git cat-file -p HEAD:mergedriver.info)
0000000   t   e   s   t       c   o   n   f   l   i   c   t   -   o   n
0000020   -   a   u   t   o   -   m   e   r   g   e  \n
0000034

How to solve this problem?


Solution

  • Since you are using <<<, then I guess you're using bash, so you can use mapfile to split your variable into an array, one element per line:

    $ echo "$mergedriverinfo"
    test
    conflict-on-auto-merge
    $ mapfile -t lines <<<"$mergedriverinfo"
    $ echo "${lines[0]}"
    test
    $ echo "${lines[1]}"
    conflict-on-auto-merge
    

    So your project key is element 0 and the repo slug is element 1.