Unix parsing pipe delimited format string in ksh

2019-02-25 22:17发布

I am writing ksh script to parse a pipe delimited string

export dummy="abc"  
echo "123|456|789" | awk '{split($0,output,"|"); print output[3] output[2] output[1]}'

above code seems to work , but I am not able to assign value of output[3] to dummy.

Is there a way to do such parsing, but I want to assign the parsing result in a variable within ksh space i.e. dummy (in above sample)?

2条回答
爷、活的狠高调
2楼-- · 2019-02-25 22:32

You can't assign awk variables (i.e. output[3]) to shell variables (i.e. dummy), you can only assign the output of awk to a variable, e.g.

export dummy=`echo "123|456|789" | awk -F'|' '{ print $3; }'`

However, awk is a bit overkill here, cut will work just as well:

export dummy=`echo "123|456|789" | cut -d'|' -f3`
查看更多
小情绪 Triste *
3楼-- · 2019-02-25 22:51

The shell can do it:

line="123|456|789"
IFS='|' read a b c <<END
$line
END
echo $c  # => 789
查看更多
登录 后发表回答