How to split a delimited string into an array in awk?

后端 未结 9 941
不思量自难忘°
不思量自难忘° 2020-11-29 16:58

How to split the string when it contains pipe symbols | in it. I want to split them to be in array.

I tried

echo \"12:23:11\" | awk \'{s         


        
9条回答
  •  旧时难觅i
    2020-11-29 17:13

    I do not like the echo "..." | awk ... solution as it calls unnecessary fork and execsystem calls.

    I prefer a Dimitre's solution with a little twist

    awk -F\| '{print $3 $2 $1}' <<<'12|23|11'
    

    Or a bit shorter version:

    awk -F\| '$0=$3 $2 $1' <<<'12|23|11'
    

    In this case the output record put together which is a true condition, so it gets printed.

    In this specific case the stdin redirection can be spared with setting an awk internal variable:

    awk -v T='12|23|11' 'BEGIN{split(T,a,"|");print a[3] a[2] a[1]}'
    

    I used ksh quite a while, but in bash this could be managed by internal string manipulation. In the first case the original string is split by internal terminator. In the second case it is assumed that the string always contains digit pairs separated by a one character separator.

    T='12|23|11';echo -n ${T##*|};T=${T%|*};echo ${T#*|}${T%|*}
    T='12|23|11';echo ${T:6}${T:3:2}${T:0:2}
    

    The result in all cases is

    112312
    

提交回复
热议问题