shell command to truncate/cut a part of string
Solution 1
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.
Solution 2
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
Solution 3
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.
Solution 4
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.
Jill448
Updated on July 09, 2022Comments
-
Jill448 almost 2 years
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
-
Axel Beckert almost 5 yearsYou can omit the
1
in the cut command and the parentheses in theawk
statement which makes it even shorter:VERSION=($(grep -r "Version:" /path/file.spec| awk '{print $2}' | cut -d. -f-3))