#!/bin/sh cat << 'EEE' > /dev/null /* ssort .... sort command parser, bourne-shell script * Copyright (C) 2018,2019 Momi-g * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ EEE #optcheck-------- if [ "$1" = "-h" ] ; then cat << 'EEE' HowTo (ssort, simple sort command parser) option: -h (this) ...and 'sort' command option ------ ex) echo " q 12 AAA w 03 BBB e 5 CCC t 3 BBB y 03 ZZZ " | ssort 2n,3r,1 # parse 'sort -b -k 2,2n -k 3,3r -k 1,1' >>> y 03 ZZZ t 3 BBB w 03 BBB e 5 CCC q 12 AAA ex) ... | ssort 1n -o out.csv #... $1 must be a sequence string. 2,3nr,1: sort sequence. second field - third f - first f. n or r etc: sort option. see 'sort --help'. n:num r:reverse. o,M,f,V... etc. ...99.9% users only use n/r option. EEE exit 1 fi buf=`echo $1 | awk '$1 ~ /^-/{print $0}' ` if [ "$buf" != "" ] || [ $# -eq 0 ] ; then echo "$0: args err. see -h. sleep." >/dev/stderr sleep 1000 exit 1 fi # https://abicky.net/2011/07/24/174632/ # # ふつーに書いたらsort -k 1 -k 2n -k 3n # が分かりやすいが、これは予想通りに働かない。 # sort -k 1-3 -k 2-3n -k 3-3n # みたいに以降のキー全てを対象としてしまうため。 # ついでに文字の位置指定も省略されてる。 # 1.1は1つめのキーの1文字目を意味する。 # # sort -k 1.1,1.$ -k 2.2,2.$n -k 3.2,3.$n # が正しいイメージ。ただし$は終端を表しているけど、sortでは$がない。 # .を省略するのが唯一の終端となるので、最終的には # sort -k 1.1,1 -k 2.2,2n -k 3.2,3n # が暗黙なしにちゃんと書いた場合の動作となる。 # 第二以降のキーは頭にスプリッタが入るので2.1ではスプリッタ自体が入る。 # -bなら空白を無視する一般的な動作になる。 # 別にそれでも実質的には問題ないけど、2-4文字の部分だけ比較ソートしたいなら # 2.2,2.4 ではなく2.3,2.5となる。 # つまり、sortをそのまま直接用いるのは超めんどくさい。 # 自分で使いやすいエイリアスを作っておくことを念頭に作られている感じ? #cmd="2n,3,1" #sort -k 1.1,1 -k 2.2,2n -k 3.2,3n func_ssrt() { ( ssrt_cmd="$1" shift ssrt_str=`echo "$ssrt_cmd" | tr -d ' ' | tr ',' '\n' | sed -e 's#^[0123456789]#& #g' | while read -r ssrt_A ssrt_B do if [ $ssrt_A -eq 1 ] ; then echo "-k 1.1,1$ssrt_B" else echo "-k $ssrt_A.1,$ssrt_A$ssrt_B" fi done | tr '\n' ' ' ` sort -b "$@" $ssrt_str ) } #--- main # ssort 2n,3r,1 -a -b ... format pos is fixed to '$1' ( bk_lcl=`set` export LC_ALL=C export LANG=C pf1='( eval "$bk_lcl" ; cat - )' func_ssrt "$@" | eval "$pf1")