How to parse a string in a shell script

I want to parse the following line in a shell script.

VERSION=2.6.32.54-0.11.def 

Here I want to get two values.

 first = 263254 second = 11 

I use the following to get the first value:

 first=`expr substr $VERSION 1 9| sed "s/\.//g" |sed "s/\-//g"` 

to get the second:

 second=`expr substr $VERSION 10 6| sed "s/\.//g" |sed "s/\-//g"` 

Using the code above, the output is:

 first=263254 second=11 

The result will not be consistent if the version is changed to:

 VERSION=2.6.32.54-0.1.def 

Here the second value will become 1d, but I want it to only output pin 1.

How can I directly analyze the number after the '-' and before the '.d'?

+2
source share
6 answers
 $ first=$(echo $VERSION | cut -d- -f1 | sed 's/\.//g') $ second=$(echo $VERSION | cut -d- -f2 | cut -d. -f2) 
+3
source

you do not need multiple processes (sed | sed | sed ...). one process with awk should work.

if you have VERSION=xxxx as a string:

to get the first:

 awk -F'[-=]' '{gsub(/\./,"",$2)}$0=$2' 

to get the second:

 awk -F'-|\\.def' '{split($2,a,".")}$0=a[2]' 

test

first

 kent$ echo "VERSION=2.6.32.54-0.1.def"|awk -F'[-=]' '{gsub(/\./,"",$2)}$0=$2' 263254 

second

 kent$ echo "VERSION=2.6.32.54-0.1.def"|awk -F'-|\\.def' '{split($2,a,".")}$0=a[2]' 1 kent$ echo "VERSION=2.6.32.54-0.1234.def"|awk -F'-|\\.def' '{split($2,a,".")}$0=a[2]' 1234 

if you have VERSION=xxx as the $VERSION variable:

 first: awk -F'-' '{gsub(/\./,"",$1)}$0=$1' second: awk -F'-|\\.def' '{split($2,a,".")}$0=a[2]' 

test

 VERSION=2.6.32.54-0.1234.def kent$ echo $VERSION|awk -F'-' '{gsub(/\./,"",$1)}$0=$1' 263254 7pLaptop 11:18:22 /tmp/test kent$ echo $VERSION|awk -F'-|\\.def' '{split($2,a,".")}$0=a[2]' 1234 
+3
source
 $ first=$(echo $VERSION | cut -d- -f1 | tr -d '.') $ second=$(echo $VERSION | cut -d- -f2 | cut -d. -f2) $ echo $first 263254 $ echo $second 11 
+2
source

You should use regular expressions instead of the number of characters.

 first=`sed 's/.//g' | sed 's/\(.*\)-.*/\1/'` second=`sed 's/.//g' | sed 's/.*-\([0-9]*\).*/\1/'` 

\(...\) are used to create a capture group, and \1 displays this group.

+1
source
  first=$(echo ${VERSION} | sed -e 's/^\([^-]*\)-0\.\([0-9]*\)\.def/\1/' -e 's/\.//g') second=$(echo ${VERSION} | sed -e 's/^\([^-]*\)-0\.\([0-9]*\)\.def/\2/' -e 's/\.//g') 
0
source
 $ first=$(echo $VERSION | awk -F"\." '{gsub(/-.*/,"",$4);print $1$2$3$4}') $ second=$(echo $VERSION | awk -F"\." '{print $5}' ) 
0
source

Source: https://habr.com/ru/post/1205273/


All Articles