Re: Unix script question (basic)

From: Chris F.A. Johnson (c.fa.johnson_at_rogers.com)
Date: 03/05/04


Date: 5 Mar 2004 19:07:32 GMT

On Fri, 05 Mar 2004 at 18:44 GMT, Piestiany7 wrote:
> Some time ago on these boards someone suggested a good
> way of finding out how many columns there were in a file
>
> read x < $1
> set -- $x
> columns=$#
>
> I have two questions
>
> 1) what effect is set -- $x having (ie in enabling subsequently for $# to have
> meaning)

   It places the contents of $x into the positional parameters ($1, $2
   ...); $# is the number of parameters.

> 2) if we were to put this into a loop to read every single row in the file and
> output the number of columns, can we use a construct like
><command> | while read row
>
> if so what can we have for 'command'? cat looks at a field at a time

     Cat doesn't know about fields; it just copies its input (file or
     stdin) to stdout. A while loop can read it line by line.

     But there's no need for a command; just redirect the input.

while read row
do
  set -- $row
  echo $#
done < FILE

     It would be faster, particularly with a large file, to use awk:

awk '{print NF}' FILE

-- 
    Chris F.A. Johnson                  http://cfaj.freeshell.org/shell
    ===================================================================
    My code (if any) in this post is copyright 2004, Chris F.A. Johnson
    and may be copied under the terms of the GNU General Public License


Relevant Pages

  • Re: A 64-bit binary returning a value to a 32-bit binary?
    ... the 32bit executable to write to stdout to 64bit's stdin. ... executable will then write to stdout and the 32bit will read it. ... NULL)" loop. ... I would write the input to the log file. ...
    (comp.lang.c)
  • Re: A 64-bit binary returning a value to a 32-bit binary?
    ... the 32bit executable to write to stdout to 64bit's stdin. ... executable will then write to stdout and the 32bit will read it. ... NULL)" loop. ... I would write the input to the log file. ...
    (comp.lang.c)
  • Re: copy-overlay in VI
    ... It could be done without sed & awk - as I suggested before, ... If you had a shell script in your path named "coverlay" that executed a sed ... command that read stdin and wrote stdout, ... replace those 4 lines with the stdout of coverlay. ...
    (comp.lang.cobol)
  • Shell pipe command with key pause
    ... I am wondering how to write simple shell script of "more" equivalent: ... write to stdout ... this loop is paused by key ... the script when stdin is redirected. ...
    (Debian-User)
  • Re: Forth stdin and stdout
    ... which takes stdin and stdout. ... Win32for and iForth. ... the notes in the ./dfwforth/bugs.frt file on redirection. ...
    (comp.lang.forth)