shell脚本:开头的逗号而不是结尾

问题描述 投票:0回答:1

这是我的shell脚本的一部分。

for line in `cat $1`
do
        startNum=`echo $line | awk -F "," '{print $1}'`
        endNum=`echo $line | awk -F "," '{print $2}'`
        operator=`echo $line | awk -F "," '{print $3}'`
        termPrefix=`echo $line | awk -F "," '{print $4}'`

        if [[ "$endNum" == 81* ]] || [[ "$endNum" == 33* ]] || [[ "$endNum" == 55* ]]
        then
                areaCode="${endNum:0:2}"
                series="${endNum:2:4}"
                startCLI="${startNum:6:4}"
                endCLI="${endNum:6:4}"
        else
                areaCode="${endNum:0:3}"
                series="${endNum:3:3}"
                startCLI="${startNum:6:4}"
                endCLI="${endNum:6:4}"
        fi

echo "Add,${areaCode},${series},${startCLI},${endCLI},${termPrefix},"
#>> ${File}

done

输入是csv包含下面很多行:

5557017101,5557017101,102,1694
5515585614,5515585614,102,084

shell脚本的输出:

,dd,55,5701,7101,7101,1694
,dd,55,1558,5614,5614,0848

不确定为什么逗号开始输出,而不是根据shell脚本它应该到最后。

请帮忙

shell unix
1个回答
0
投票

这是一个建议的awk命令,它应该替换你所有的shell + awk代码。这awk也照顾跟踪\r

awk -v RS=$'\r' 'BEGIN{FS=OFS=","} NF>3{
   startNum=$1; endNum=$2; termPrefix=$4; 
   if (endNum ~ /^(81|33|55)/) {
      areaCode=substr(endNum,1,2); series=substr(endNum,3,4)
   }
   else {
      areaCode=substr(endNum,1,3); series=substr(endNum,4,3)
   } 
   startCLI=substr(startNum,7,4); endCLI=substr(endNum,7,4);
   print "Add", areaCode, series, startCLI, endCLI, termPrefix
}' file

Add,55,5701,7101,7101,1694
Add,55,1558,8561,5614,084
© www.soinside.com 2019 - 2024. All rights reserved.