How to get only a chunk of a command output

Asked

Viewed 63 times

0

How do I show only the version number? Example:

GIT_VERSION=$(git --version)

echo $'git instalado com sucesso! Na versao: '$GIT_VERSION$'\n'

The output I wish is "In version: 1.20.2". I have tried with array and the sed but I couldn’t.

  • 2

    Try to use git --version | awk '{ print $3 }'. :)

  • worked! thanks!!!

2 answers

1

You specify a character range you want to print.

Try:

echo $'git instalado com sucesso! Na versao: '${GIT_VERSION:12:17}$'\n'

Explaining ${VAR_NOME:Primeiro caractere a ser impresso: ultimo a ser impresso}

1

Whereas the exit from the control git --version is something like git version 1.2.3, then at the bottom is a matter of getting the final stretch. There are several ways to do this.

One is using the commando cut:

GIT_VERSION=$(git --version | cut -d" " -f 3)

The option -d" " indicates that the space (denoted by " ") should be used as separator, i.e., the output will be separated into 3 parts: git, version and the version number. Next, -f 3 indicates that we only want the third field, which in this case is the version number.


Other alternative (already indicated in the comments) is to use awk:

GIT_VERSION=$(git --version | awk '{print $3}')

The idea is the same as cut, the difference is that space is already the separator default, and the third field is accessed by $3.


It is also possible with sed:

GIT_VERSION=$(git --version | sed -e 's/.* \([^ ][^ ]*\)[ ]*$/\1/')

But I find it unnecessarily complicated - even though it works, regex is not always the best solution.
But anyway, the regex takes a string other than spaces ([^ ]) in the string end ($), and puts in a catch group (denoted by parentheses). And in substitution, I use only the value of the group (\1), ignoring the rest of the line.


You can even turn the output of the command into an array:

dados=($(git --version))
GIT_VERSION=${dados[2]}

The extra parentheses around the command turn the output into a array, and the version will be in the third position (remembering that the first is zero, so I used the index 2).

It is not as straightforward as the previous options, and is more useful if you need all fields separately. But if you only want the version number, the first 2 options seem better.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.