#!/usr/bin/awk -f # The MIT License (MIT) # # Copyright © 2024 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. # ptsv [column names...] # # Pick Tab Separated-Values, trying to match the column names given using the # first line from stdin. Matching works by first trying exact matching, then # case-insensitive matching, when there's no exact match, finally giving up # when there's no match either way. BEGIN { FS = "\t" for (i = 1; i < ARGC; i++) { colnames[++n] = 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 { for (i = 1; i <= n; i++) lownames[i] = tolower(colnames[i]) for (i = 1; i <= NF; i++) { j = findcol(colnames[i], lownames[i]) if (j > 0) pick[++numcols] = j } if (numcols == 0) exit } { for (i = 1; i <= numcols; i++) { if (i > 1) printf "\t" printf "%s", $(pick[i]) } printf "\n" fflush() }