我有一个包含多行字符串的变量。我需要读取前两行并根据它们的值进行一些处理。 我怎么能这样做?
我的变量中的样本值是
Description: some value
Entity: Some value
Fixed
我需要将前两行(描述和实体)作为不同的变量。
答案 0 :(得分:3)
使用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
答案 1 :(得分:2)
例如:
$ 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