Csh: first character of an arg is '-': Solution
Tom Christiansen
tchrist at convex.COM
Mon Oct 8 01:22:20 AEST 1990
In article <JAK.90Oct7001815 at bimini.cs.brown.edu> jak at cs.brown.edu writes:
>Before I get flooded with more replies, let me post the answer that
>barnett at crdgw1.ge.com, raymond at math.berkeley.edu and
>christos at theory.tn.cornell.edu all basically gave me:
>foreach i ($*)
> if ( $i =~ -* ) then
> # is an arg
> else
> # is not
> endif
>end
>Apart from the typo ~= instead of =~ , my problem was that I was quoting
>the right hand side, thinking that I did not want filename expansion,
>though as Raymond pointed out, I *do* want filename expansion, but
>expansion in the context of the left hand side, not of the current
>directory. It seems like strange magic to me, but it works...
Yes, it is strange magic; welcome to the csh. This solution won't work
if one of the arguments is a built-in test, like -x. Try it. Csh
claims that it is missing a file name. If you write it this way:
if ( x$i =~ x-* ) then
you get around that problem.
>So thank-you for the replies. By the way, no-one yet has answered my
>second question: can you extract a character from a word? (Again, no
>forking allowed).
Hm... in Bourne or csh but without forking??? That's a pretty tough order.
I'm not a power ksh user, but I did cobble something together. In ksh,
you should be able to hack off the end of the variable (call it $x). You
use the ${x%pat} syntax. The problem is you don't know the pattern, which
would be a bunch of ?'s, as many as one less than the length of the
string. I managed to do it one at a time until small enough:
y='foobar'
x="$y"
while [ ${#x} -ne 1 ]; do x=${x%?}; done
echo y is $y, x is $x
This shouldn't take any forking, but is pretty lame I must admit. But
what do you expect for a command interpreter trying to pass itself off as
a programming language? :-( It really needs a ${var#s/a/b/#} with real
regexps, so I can get some reasonable back-referencing (you know, \1 stuff).
Again, there may be better ways that I don't know in ksh, but I did scan
the man page.
If you'd chosen to write your script in perl, you could have said
something like any of these:
$x=substr($y,0,1);
or
($x) = ($y =~ /^(.)/);
or
($x = $y) =~ s/^(.).*/$1/;
Again, no forks involved.
--tom
--
"UNIX was never designed to keep people from doing stupid things, because
that policy would also keep them from doing clever things." [Doug Gwyn]
More information about the Comp.unix.shell
mailing list