bash:将逗号分隔长的列表拆分为两部分

时间:2013-10-14 10:40:43

标签: bash list split

我有一个bash脚本,它从外部命令中读取逗号和空格分隔的服务器名称列表:

server_0.example.com, server_1.example.com, ..., server_70.example.com

脚本应运行外部命令,该命令接受该表单中的服务器列表,但一次限制为50个服务器。因此,我需要将其拆分为两个大小相同的列表:

server_0.example.com, server_1.example.com, ..., server_35.example.com

server_35.example.com, server_36.example.com, ..., server_70.example.com

1 个答案:

答案 0 :(得分:2)

这可以是一种方法:

awk -F, '{for (i=1; i<=NF/2; i++) printf "%s, ", $i} <-- prints first half
         {printf "\n"} <--- prints new line
         {for (i=NF/2+1; i<=NF; i++) printf "%s, ", $i}  <-- prints second half
         {printf "\n"} <--- prints new line
        '

测试

$ awk -F, '{for (i=1; i<=NF/2; i++) printf "%s, ", $i} {printf "\n"} {for (i=NF/2+1; i<=NF; i++) printf "%s, ", $i} {printf "\n"}' <<< "server_0.example.com, server_1.example.com, ..., server_70.example.com"
server_0.example.com,  server_1.example.com, 
 ...,  server_70.example.com, 

更新

当NF为奇数时,不要跳过一个值:

awk -F, '{for (i=1; i<=int(NF/2); i++) printf "%s, ", $i} <-- prints first half
         {printf "\n"} <--- prints new line
         {for (i=int(NF/2)+1; i<=NF; i++) printf "%s, ", $i}  <-- prints second half
         {printf "\n"} <--- prints new line
        '