我有一个包含多行字符串的变量。我需要阅读前两行并根据它们的值进行一些处理。我怎样才能做到这一点 ?
我的变量中的样本值是
Description: some value
Entity: Some value
Fixed
我需要将前两行(描述和实体)作为不同的变量。
与sed
:
$ echo "$var"
Description: some value
Entity: Some value
Fixed
$ var2=$(sed -n 1p <<< "$var")
$ var3=$(sed -n 2p <<< "$var")
$ echo $var2
Description: some value
$ echo $var3
Entity: Some value
如果您只想要这些值:
$ var2=$(sed -n '1s/.*: //p' <<< "$var")
$ var3=$(sed -n '2s/.*: //p' <<< "$var")
$ echo $var2
some value
$ echo $var3
Some value
同样的事情grep
:
$ var2=$(grep Description <<< "$var")
$ var3=$(grep Entity <<< "$var")
$ echo $var2
Description: some value
$ echo $var3
Entity: Some value
仅值:
$ var2=$(grep -Po "Description: \K.*" <<< "$var")
$ var3=$(grep -Po "Entity: \K.*" <<< "$var")
$ echo $var2
some value
$ echo $var3
Some value
例如:
$ echo "$MYVAR"
Description: some value
Entity: Some value
Fixed
$ VAR1=$(echo "$MYVAR" | sed -n 1p)
$ VAR2=$(echo "$MYVAR" | sed -n 2p)
VAR1
现在分别包含第一行和VAR2
第二行MYVAR
:
$ echo $VAR1
Description: some value
$ echo $VAR2
Entity: Some value