+
+dbmeta_autogroup(){
+ sed -E '
+ # strip empty group field
+ s;\r \\$;\r;;
+ h; # save original dataset
+
+ # strip common suffixes of web video sites
+ s;-([0-9a-zA-Z_-]{11}|ph[0-9a-f]{13}|xh[0-9a-zA-Z]{5}|[0-9]{6,})\r;-\r;;
+
+ # perform auto grouping if group id is missing or empty
+ /\r$/bAUTOGROUP;
+
+ # only perform ordering if manual group id is present
+ /\r .+$/bAUTOORDER;
+
+ b; # pass invalid records without processing
+
+ :AUTOORDER
+ # strip all fields but the name
+ s;^([^\t]+ [^\t]+ [^\t]+ [^\t]+ [^\t]+ )([^\r]+)\r (.+)$;\2;
+
+ # reduce to numerals
+ s;[^0-9]+;;g;
+
+ # append ordering field to dataset
+ H; g; s;\n;\t;;
+ b;
+
+ :AUTOGROUP
+ # strip all fields but the name
+ s;^[^\t]+ [^\t]+ [^\t]+ [^\t]+ [^\t]+ ;;
+
+ # replace all numeric parts and append numerals to an ordering field
+ # the group id will be made up of only the non-numeric character frame
+ # the ordering field will hold all numbers from the name
+ :X s;^([^0-9]*)([0-9]+)([^\r]*)\r\t?([0-9]*)$;\1\r\3\r \4\2;; tX;
+
+ # append group id and ordering field to dataset
+ H; g; s;\n;\t;;
+ ' "$@"
+}