DEV Community

Query Filter
Query Filter

Posted on

awk

#!/bin/bash
# Usage:
#   ./roundFilter.sh file.csv decimals col1 [col2 ... colN]
#
# Example:
#   ./roundFilter.sh data.csv 2 45 12 78

if [ "$#" -lt 3 ]; then
    echo "Usage: $0 file.csv decimals col1 [col2 ... colN]"
    exit 1
fi

file="$1"
decimals="$2"
shift 2   # remaining args are column numbers

# Convert column list to comma-separated string
cols=$(IFS=,; echo "$*")

awk -F'~' -v OFS='~' -v cols="$cols" -v dec="$decimals" '
BEGIN {
    n = split(cols, cidx, ",")
    fmt = "%." dec "f"
    factor = 10 ^ dec
}
{
    for (i = 1; i <= n; i++) {
        col = cidx[i]

        # Ensure column exists
        if (col <= NF && $col ~ /^-?[0-9]*\.?[0-9]+$/) {

            # Manual rounding to avoid IEEE-754 issues
            rounded = int($col * factor + 0.5) / factor
            $col = sprintf(fmt, rounded)
        }
    }

    # Print full record (joined using OFS="~")
    print
}
' "$file"

Enter fullscreen mode Exit fullscreen mode

Top comments (0)