Bash script get/extract specific info/word from output info

Viewed 94

the command nvcc --version outputs the following:

nvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2019 NVIDIA Corporation
Built on Wed_Oct_23_21:14:42_PDT_2019
Cuda compilation tools, release 10.2, V10.2.89

I'm trying to get the cuda version which in this case is 10.2 from the 4th line.

Therefore i tried the following:

cudaVersion="$(nvcc --version| grep 'Cuda compilation ')"
echo "$cudaVersion"

this gives me however the whole line as an output. However i just want to assign the version to cudaVersion

I believe this must work with cut, however i can't get it

Thanks in advance

2 Answers

With your shown samples, could you please try following. Written and tested in GNU grep.

nvcc --version | grep -oP '^Cuda compilation.*release \K[0-9]+\.[0-9]+'

Explanation: Adding detailed explanation for above.

nvcc --version |  ##Running  nvcc --version command and sending its output to grep command.
grep -oP          ##Using grep command using -P option for enabling PCRE ERE here.  
'^Cuda compilation.*release \K[0-9]+\.[0-9]+'
                  ##Checking if line starts Cuda compilation till release space.
                  ##\K will skip till matched value(since we don't want in output) dot and digits.


OR with any awk:

nvcc --version | 
awk '
  /^Cuda compilation.*release / && match($0,/release [0-9]+\.[0-9]+/){
    print substr($0,RSTART+8,RLENGTH-8)
}
'

Explanation: Adding detailed explanation for above.

nvcc --version |      ##Running command nvcc --version sending output to awk here as input.
awk '                 ##starting awk program from here.
  /^Cuda compilation.*release / && match($0,/release [0-9]+\.[0-9]+/){
                      ##Checking condition if line starts from Cuda compilation till release AND using match function to release space digits dot digits here.
    print substr($0,RSTART+8,RLENGTH-8)  ##printing sub string with matches value and printing Only version here.
}
'

You can use

cudaVersion="$(nvcc --version | awk '/Cuda compilation/{sub(/,$/,"", $5); print $5}')"

Here, the lines (record) is split into fields with whitespace and the line with Cuda compilation is searched for, and once found, prints Field 5 value without trailing comma.

See the online demo:

s='nvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2019 NVIDIA Corporation
Built on Wed_Oct_23_21:14:42_PDT_2019
Cuda compilation tools, release 10.2, V10.2.89'
awk '/Cuda compilation/{sub(/,$/,"", $5); print $5}' <<< "$s"
## => 10.2

See a test performed on a GPU instance: enter image description here

Related