Skip site navigation (1)Skip section navigation (2)
Date:      Wed, 27 Oct 2010 22:04:52 -0400 (EDT)
From:      vogelke+unix@pobox.com (Karl Vogel)
To:        freebsd-questions@freebsd.org
Subject:   Re: [OT] writing filters in sh
Message-ID:  <20101028020452.A282DBF80@kev.msw.wpafb.af.mil>
In-Reply-To: <20101027212841.GA67716@guilt.hydra> (message from Chad Perrin on Wed, 27 Oct 2010 15:28:41 -0600)

next in thread | previous in thread | raw e-mail | index | archive | help
>> On Wed, 27 Oct 2010 15:28:41 -0600, 
>> Chad Perrin <perrin@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



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?20101028020452.A282DBF80>