how to parse a string in Shell script

2019-05-11 12:40发布

问题:

I want to parse the following string in shell script.

VERSION=2.6.32.54-0.11.def

Here I want to get two value.

first = 263254
second = 11

I am using 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 above code the output is:

first=263254
second=11

The result wont be consistent if version is changed to:

VERSION=2.6.32.54-0.1.def

Here second value will become 1d, but I want it give output of 1 only.

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

回答1:

$ first=$(echo $VERSION | cut -d- -f1 | sed 's/\.//g')
$ second=$(echo $VERSION | cut -d- -f2 | cut -d. -f2)


回答2:

you don't need multiple processes (sed|sed|sed...). single process with awk should work.

if you have VERSION=xxxx as 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 variable $VERSION:

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:

$ first=$(echo $VERSION | cut -d- -f1 | tr -d '.')
$ second=$(echo $VERSION | cut -d- -f2 | cut -d. -f2)
$ echo $first
263254
$ echo $second
11


回答4:

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 capturing group, and \1 output this group.



回答5:

 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')


回答6:

$ first=$(echo $VERSION | awk -F"\." '{gsub(/-.*/,"",$4);print $1$2$3$4}')
$ second=$(echo $VERSION | awk -F"\." '{print $5}' )


标签: shell