使用Bash

时间:2015-05-21 16:25:56

标签: linux bash split

我有一个包含多个子网的巨大文件,如下所示:

234.245.34.324/24
234.214.23.34/24
234.344.234.14/24
234.214.234.314/24
234.245.34.324/23
234.214.23.34/22
234.344.234.14/22
234.214.234.314/23
234.245.34.324/24
234.214.23.34/20
234.344.234.14/21
234.214.234.314/20

它们都具有不同的IP地址和相同的子网,例如我有2340个子网/24

现在,我想将这些拆分为2个文件,其中50%的/24拆分都在每个文件中,/23/22 /21等相同。

我知道我可以与split -l分开,但这只会给我一条线。目的是在两个文件中获得相同数量的子网。

这应该在Linux bash中完成,因为它将自动化。

任何人都知道怎么做?

1 个答案:

答案 0 :(得分:1)

假设您有bash 4.3可用,避免使用临时文件的实现可能如下所示:

#!/usr/bin/env bash
#      ^- important: use bash, not sh, as shell

# sort into an array per mask length
declare -A masklens=( )
while IFS=/ read -r addr masklen; do
  [[ $addr ]] || continue
  masklens[$masklen]=1
  declare -a "addrs_${masklen}"
  declare -n addrs="addrs_${masklen}"
  addrs+=( "$addr" )
done

exec 3>"$1" 4>"$2" # open output files
for masklen in "${!masklens[@]}"; do
  declare -n addrs="addrs_${masklen}"
  fmt="%s/${masklen}\n"
  printf "$fmt" "${addrs[@]:0:(${#addrs[@]} + 1) / 2}" >&3
  if (( ${#addrs[@]} > 1 )); then
    printf "$fmt" "${addrs[@]:(${#addrs[@]} + 1) / 2}" >&4
  fi
done
exec 3>&- 4>&- # close output files

...被调用为......

$ splitfiles out1 out2 <infile
相关问题