User Tools

Site Tools


howtos:convert_a_csv_to_data_group_format_for_import

Inspired by Jason Rahm I have made a Bash version of the converter script:

#!/bin/bash

# read IP addresses from CSV file into array
mapfile -t ipaddrs < dg_ipaddrs.csv

# loop through array and format each IP address
for addr in "${ipaddrs[@]}"; do
  # remove any leading/trailing whitespace
  addr="$(echo -e "${addr}" | tr -d '[:space:]')"

  # split line into fields on comma delimiter
  IFS=',' read -ra fields <<< "$addr"

  # check if first field contains a network mask or prefix length. The ${fields[0],,} syntax is used to convert the contents of the fields[0] variable to lowercase.
  if [[ "${fields[0]}" == */* ]] || [[ "${fields[0],,}" == *"mask"* ]] || [[ "${fields[0],,}" == *"prefixlen"* ]]; then
    # check if second field is empty
    if [[ -z "${fields[1]}" ]]; then
      echo "network ${fields[0]},"
    else
      value="${fields[1]}"
      echo "network ${fields[0]} := ${value},"
    fi
  else
    # check if second field is empty
    if [[ -z "${fields[1]}" ]]; then
      echo "host ${fields[0]},"
    else
      value="${fields[1]}"
      echo "host ${fields[0]} := ${value},"
    fi
  fi
done > dg_formatted.txt
howtos/convert_a_csv_to_data_group_format_for_import.txt · Last modified: 19/03/2023 16:06 by domingo