0

我有一个 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
4

1 回答 1

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
        '
于 2013-10-14T10:47:05.973 回答