[OT] writing filters in sh

Devin Teske dteske at vicor.com
Thu Oct 28 17:24:21 UTC 2010


On Wed, 2010-10-27 at 15:28 -0600, Chad Perrin wrote:
> I know that in sh you can get the contents out of files specified as
> command line arguments:
> 
>     while read data; do
>       echo $data
>     done <$@
> 
> I know you can also get the contents of files from pipes and redirects:
> 
>     while read data; do
>       echo $data
>     done
> 
> In Perl, you can use a single construct to do both and, unlike the first
> sh example, it can also take multiple filenames as arguments and
> effectively concatenate their contents:
> 
>     while (<>) {
>       print $_;
>     }
> 
> I'm not exactly an *expert* in sh, in part because when things start
> getting "interesting" while I'm writing shell scripts I tend to just use
> a more robust language like Perl.  Please let me know if there's some way
> to use a simple idiom like the Perl example to get the same results in
> sh.
> 


see here:
http://druidbsd.sf.net/download/sysrc.txt

For example (NOTE: this is just an example -- the function itself is
inefficient when one considers instead `tail -r file' and `tail -r <
file' and `cat file | tail -r', though the function serves as a good
example of how to achieve what you want):

# ... | lrev
# lrev $file ...
#
# Reverse lines of input. Unlike rev(1) which reverses the ordering of
# characters on a single line, this function instead reverses the line
# sequencing.
#
# For example, the following input:
#
# 	Line 1
# 	Line 2
# 	Line 3
#
# Becomes reversed in the following manner:
#
# 	Line 3
# 	Line 2
# 	Line 1
#
lrev()
{
	local stdin_rev=
	if [ $# -gt 0 ]; then
		#
		# Reverse lines from files passed as positional arguments.
		#
		while [ $# -gt 0 ]; do
			local file="$1"
			[ -f "$file" ] && lrev < "$file"
			shift 1
		done
	else
		#
		# Reverse lines from standard input
		#
		while read -r LINE; do
			stdin_rev="$LINE
$stdin_rev"
		done
	fi

	echo -n "$stdin_rev"
}




-- 
Cheers,
Devin Teske

-> CONTACT INFORMATION <-
Business Solutions Consultant II
FIS - fisglobal.com
510-735-5650 Mobile
510-621-2038 Office
510-621-2020 Office Fax
909-477-4578 Home/Fax
devin.teske at fisglobal.com

-> LEGAL DISCLAIMER <-
This message  contains confidential  and proprietary  information
of the sender,  and is intended only for the person(s) to whom it
is addressed. Any use, distribution, copying or disclosure by any
other person  is strictly prohibited.  If you have  received this
message in error,  please notify  the e-mail sender  immediately,
and delete the original message without making a copy.

-> END TRANSMISSION <-



More information about the freebsd-questions mailing list