#!/bin/sh # The MIT License (MIT) # # Copyright © 2020-2025 pacman64 # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the “Software”), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # dtsv [column names...] # # Drop Tab Separated-Values, ignoring all columns given, and keeping all the # others. The column names given are matched using the first line from stdin. # Matching works by first trying exact matching, then by case-insensitive # matching, when there's no exact match, finally giving up when there's no # match either way. case "$1" in -h|--h|-help|--help) awk '/^# +dtsv /, /^$/ { gsub(/^# ?/, ""); print }' "$0" exit 0 ;; esac [ "$1" = "--" ] && shift command="awk" if [ -p 1 ] || [ -t 1 ]; then command="stdbuf -oL awk" fi ${command} -F "\t" ' BEGIN { for (i = 1; i < ARGC; i++) { colnames[++n] = ARGV[i] lownames[n] = tolower(ARGV[i]) delete ARGV[i] } } function findcol(name, lowname, i) { for (i = 1; i <= NF; i++) if (name == $i) return i for (i = 1; i <= NF; i++) if (lowname == tolower($i)) return i if (1 <= name && name <= NF) return name + 0 if (name < 0 && -name <= NF) return NF + name + 1 return 0 } { gsub(/\r$/, "") } NR == 1 { numcols = NF for (i = 1; i <= numcols; i++) keep[i] = 1 colsused = numcols for (i = 1; i <= n; i++) { j = findcol(colnames[i], lownames[i]) if (j > 0) { keep[j] = 0 colsused-- } if (j == 0) { fmt = "\x1b[31mno column match for \"%s\"\x1b[0m\n" printf(fmt, colnames[i]) > "/dev/stderr" errors++ } } if (errors > 0) exit 1 if (colsused == 0) exit } { c = 0 for (i = 1; i <= numcols; i++) { if (keep[i] == 1) { if (c > 0) printf "\t" printf "%s", $i c++ } } printf "\n" } ' "$@"