[OT] writing filters in sh

Karl Vogel vogelke+unix at pobox.com
Thu Oct 28 02:05:55 UTC 2010


>> On Wed, 27 Oct 2010 15:28:41 -0600, 
>> Chad Perrin <perrin at apotheon.com> said:

C> In Perl, you can use a single construct to [read files or pipes], and it
C> can also take multiple filenames as arguments and effectively
C> concatenate their contents:

C> while (<>) { print $_; }

C> Please let me know if there's some way to use a simple idiom like the
C> Perl example to get the same results in sh.

   AFAIK, you can easily do *one* input and output file, but not multiple
   input files like the Perl "diamond" operator unless you want to play
   games with the argument list.  This works with sh, ksh, and bash on
   FreeBSD and Solaris:

   #!/bin/sh
   # filter: handle input/output files or stdin/stdout.
   # usage: filter [input] [output]
   # ie:    filter           read stdin, write stdout
   #        filter in        read file "in", write stdout
   #        filter in out    read file "in", write file "out"
   #        filter - out     read stdin, write file "out"
   PATH=/usr/local/bin:/bin:/usr/bin; export PATH

   case "$1" in
       "")  ;;
       "-") shift ;;
       *)   exec <"$1"; shift ;;
   esac

   case "$1" in
       "")  ;;
       *)   exec >"$1" ;;
   esac

   wc       # or whatever
   exit 0

-- 
Karl Vogel                      I don't speak for the USAF or my company

We seem not to have learned a basic lesson of history: Capitalism harnesses
self-interest; socialism exhausts itself trying to kill it.  --Linda Bowles


More information about the freebsd-questions mailing list