So here is the bash function, where the arguments are exactly like sort. Support files and pipes.
function skip_header_sort() { if [[ $# -gt 0 ]] && [[ -f ${@: -1} ]]; then local file=${@: -1} set -- "${@:1:$(($#-1))}" fi awk -vsargs="$*" 'NR<2{print; next}{print | "sort "sargs}' $file }
How does it work. This line checks to see if there is at least one argument and whether the last argument is a file.
if [[ $# -gt 0 ]] && [[ -f ${@: -1} ]]; then
This saves the file as a separate argument. Since we're going to erase the last argument.
local file=${@: -1}
Here we will remove the last argument. Since we do not want to pass this as a sort argument.
set -- "${@:1:$(($#-1))}"
Finally, we execute the awk part by passing arguments (minus the last argument, if it was a file) to sort in awk. This was originally proposed by Dave and modified to accept sorting arguments. We rely on the fact that $file will be empty if we pipe, therefore it is ignored.
awk -vsargs="$*" 'NR<2{print; next}{print | "sort "sargs}' $file
An example of using a comma-separated file.
$ cat /tmp/test A,B,C 0,1,2 1,2,0 2,0,1
flu Feb 14 '18 at 22:37 2018-02-14 22:37
source share