Jill448
Jill448

Reputation: 1793

shell command to truncate/cut a part of string

I have a file with the below contents. I got the command to print version number out of it. But I need to truncate the last part in the version file

file.spec:

Version: 3.12.0.2

Command used:

VERSION=($(grep -r "Version:" /path/file.spec | awk  '{print ($2)}'))

echo $VERSION

Current output : 3.12.0.2

Desired output : 3.12.0

Upvotes: 2

Views: 25136

Answers (4)

Adrian Frühwirth
Adrian Frühwirth

Reputation: 45566

There is absolutey no need for external tools like awk, sed etc. for this simple task if your shell is POSIX-compliant (which it should be) and supports parameter expansion:

$ cat file.spec
Version: 3.12.0.2
$ version=$(<file.spec)
$ version="${version#* }"
$ version="${version%.*}"
$ echo "${version}"
3.12.0

Upvotes: 9

Kent
Kent

Reputation: 195039

if you only grep single file, -r makes no sense.

also based on the output of your command line, this grep should work:

grep -Po '(?<=Version: )(\d+\.){2}\d+' /path/file.spec

gives you:

3.12.0

the \K is also nice. worked for fixed/non-fixed length look-behind. (since PCRE 7.2). There is another answer about it. but I feel look-behind is easier to read, if fixed length.

Upvotes: 1

Chris Seymour
Chris Seymour

Reputation: 85785

You could use this single awk script awk -F'[ .]' '{print $2"."$3"."$4}':

$ VERSION=$(awk -F'[ .]' '{print $2"."$3"."$4}' /path/file.spec)

$ echo $VERSION
3.12.0

Or this single grep

$ VERSION=$(grep -Po 'Version: \K\d+[.]\d+[.]\d' /path/file.spec)

$ echo $VERSION
3.12.0

But you never need grep and awk together.

Upvotes: 2

girardengo
girardengo

Reputation: 725

Try this:

VERSION=($(grep -r "Version:" /path/file.spec| awk  '{print ($2)}' | cut -d. -f1-3))

Cut split string with field delimiter (-d) , then you select desired field with -f param.

Upvotes: 4

Related Questions