Here is a bit of somewhat hairy bash code to similarly sort the shadow/gshadow files safely (using vipw -s/vigr -s) and in-place from the command line:
EDITOR="/usr/bin/vi -c \"1,\\\$!awk 'BEGIN {FS = \\\":\\\"} FNR==NR {x2[\\\$1] = \\\$0; next} \\\$1 in x2 {print x2 [\\\$1]x2[\\\$1]}' - /etc/passwdpasswd\" ^V^J
:wq\"-c \"wq! \" >/dev/null 2>&1" vipw -s
EDITOR="/usr/bin/vi -c \"1,\\\$!awk 'BEGIN {FS = \\\":\\\"} FNR==NR {x2[\\\$1] = \\\$0; next} \\\$1 in x2 {print x2 [\\\$1]x2[\\\$1]}' - /etc/groupgroup\" ^V^J
-c \"wq! :wq\"\" >/dev/null 2>&1" vigr -s
NOTE:
^V^Jis CtrlVCtrlJ which generates a new line - this new line is needed to separate the vim command lines.vi -cpasses the command to the vim editor which is assigned to be the editor forvipw/vigrby theEDITORvariable-  The awk code sorts 
shadowbypasswd(andgshadowbygroup) - The backslashes are just the multiple levels of escape needed corresponding to the quotation levels.
 - The second command (-c "wq! ") force writes and closes the sorted file. The force is necessary since shadow/gshadow are often mode 000 (i.e unwritable). Note the space between '!' and '' is necessary to prevent interpretation by the shell as '!' which references a bash event.