The following is a very simple example of what I mean by a "two-pass script":
#!/bin/bash
INPUTFILE=$1
grep '^#' "$INPUTFILE"
grep -v '^#' "$INPUTFILE" | sort
This script (let's call it twopass.sh
) takes the path, INPUTFILE
, to a file as its sole argument. It will then, first, print out all the lines in INPUTFILE
that begin with #
, in their original order. And, second, it will print in sorted order all the lines in INPUTFILE
that do not begin with #
.
For example, if the file example.txt
contains the following lines
# foo comes first
# bar comes second
# baz comes third
wobble
quux
wibble
frobozz
...then applying the twopass.sh
script to it should produce the following:
% ./twopass.sh example.txt
# foo comes first
# bar comes second
# baz comes third
frobozz
quux
wibble
wobble
How can I modify this script so that it can also perform the same operation on stdin
?
In other words, with the desired new version of the script, the line below should produce the same output as shown above:
./twopass.sh < example.txt
I am interested in answers to this question for both bash
and zsh
.