printing a substring in a bash script

2019-07-24 19:28发布

问题:

I have a string :

baseline=RAVENPLAT1.5.5.0_1.5.5.0-318_CHASSIS_PKG_193_15-AUG-2014_0350@/vobs/tlv_pvob

I'm trying to get into a variable the subtring untill the '@' sign is it possible?

回答1:

Using BASH regex:

baseline=RAVENPLAT1.5.5.0_1.5.5.0-318_CHASSIS_PKG_193_15-AUG-2014_0350@/vobs/tlv_pvob

[[ "$baseline" =~ ^([^@]+) ]] && myvar="${BASH_REMATCH[1]}"

echo "$myvar"
RAVENPLAT1.5.5.0_1.5.5.0-318_CHASSIS_PKG_193_15-AUG-2014_0350

OR else using BASH string manipulations:

myvar="${baseline%%@*}"


回答2:

Use Parameter Expansion:

$ baseline=RAVENPLAT1.5.5.0_1.5.5.0-318_CHASSIS_PKG_193_15-AUG-2014_0350@/vobs/tlv_pvob
$ echo "${baseline%%@*}"
RAVENPLAT1.5.5.0_1.5.5.0-318_CHASSIS_PKG_193_15-AUG-2014_0350


回答3:

Hope you've only 1 @ in your string -

 a=abc@b.c
 echo ` echo $a | tr @ ' ' | awk '{print $1}'`


回答4:

Try something like

x = "baseline=RAVENPLAT1.5.5.0_1.5.5.0-318_CHASSIS_PKG_193_15-AUG-2014_0350@/vobs/tlv_pvob"
y = "@"
z = ${x/$y*/$y}

Not tested - maybe the last character from z will be removed using something similar to:

${z:0:-1}