vjwilson
vjwilson

Reputation: 833

Cut a field and cut again in the result using AWK

As part of playing with AWK, I am trying to get the MariaDB version number only in the output.

# mysql -V
mysql  Ver 15.1 Distrib 10.1.48-MariaDB, for Linux (x86_64) using readline 5.1

# mysql -V | awk -F"-" '{print $1}' | awk '{print $5}'
10.1.48

Is there a workaround in AWK to make it shortened, like to avoid awk '{print $5}' again in the third pipe and make everything in single awk?.

Upvotes: 0

Views: 154

Answers (7)

Dudi Boy
Dudi Boy

Reputation: 4865

Here is the shortest awk script I could come with:

msql -V | awk '{sub("-MariaDB,","");print $5}'

Upvotes: 0

dash-o
dash-o

Reputation: 14452

Consider using the split to avoid having extra awk instance:

# msql -V | awk -F"-" '{ split($1, a, " ") ; print a[4] }'

Upvotes: 1

dawg
dawg

Reputation: 103864

You can grab it with sed:

$ echo 'mysql  Ver 15.1 Distrib 10.1.48-MariaDB, for Linux (x86_64) using readline 5.1' |
sed -nE 's/.* ([0-9][0-9.]*)-MariaDB.*/\1/p'

Or with GNU grep:

$ echo 'mysql  Ver 15.1 Distrib 10.1.48-MariaDB, for Linux (x86_64) using readline 5.1' |
ggrep -oP '[0-9][0-9.]*(?=-MariaDB)'

Either prints:

10.1.48

Upvotes: 1

tripleee
tripleee

Reputation: 189407

The direct answer to your question is that Awk lets you split a field again.

# mysql -V | awk -F"-" '{split($1, n, /[ \t]+/); print n[5] }'

Upvotes: 1

RavinderSingh13
RavinderSingh13

Reputation: 133528

With regex and without hardcoding field number could you please try following. This should be able to catch even version is 10.1.48.1.2(if in any case its there)

echo "10.1.48" | 
awk 'match($0,/([0-9]+\.){1,}[0-9]+/){print substr($0,RSTART,RLENGTH)}'

Upvotes: 1

Vitalii
Vitalii

Reputation: 2131

I would replace '-' to ' ' with gsub() resulting to this line:

mysql  Ver 15.1 Distrib 10.1.48 MariaDB, for Linux (x86_64) using readline 5.1
  $1   $2   $3   $4      $5     $6 ....

and print field number 5:

# mysql -V | awk '{gsub("-"," "); print $5}'
10.1.48

Upvotes: 1

anubhava
anubhava

Reputation: 785196

You may use [ -]+ as FS meaning 1+ of space or hyphen:

mysql -V | awk -F '[- ]+' '{print $5}'

10.1.48

Upvotes: 2

Related Questions