counting comand line args in a unix csh script

Discussion in 'Archived Threads 2001-2004' started by Ronan, Dec 11, 2001.

  1. Ronan

    Ronan Auditioning

    Joined:
    Jul 5, 2001
    Messages:
    6
    Likes Received:
    0
    I want to write a script to count command line arguments in a unix csh script.

    I have had ago but only seem to be able to count the total number of line wealther they are command line or not.

    If someone could help me alter the script below I would be very greatful.

    # Part2.2 count the number of command line arguments types.

    echo "the number of command line arguments is: "

    wc -l < [file name].
     
  2. Peter Yee

    Peter Yee Stunt Coordinator
    Supporter

    Joined:
    Aug 31, 1998
    Messages:
    105
    Likes Received:
    0
    I don't have handy access to a csh, but using bash, $#

    evaluates to the number of arguments on the command line,

    not counting argv[0] (the command name). Generically, you could use lots of other means to count the arguments. Using awk, for example, you could do:

    echo $* | awk '{print NF}'

    You could probably use sed, swapping spaces for newlines and piping the results to 'wc -l' to get a similar effect.

    -Peter
     
  3. Glenn L

    Glenn L Stunt Coordinator

    Joined:
    Jun 21, 1999
    Messages:
    56
    Likes Received:
    0
    There's dozens of different ways to do this, but you're on the right track with 'wc'.

    First examine what a command line is:

    % command arg1 arg2 arg3 ...etc

    it's one line with a bunch of words, what you want to count are the number of words. 'wc -l' counts the number of lines, 'wc -w' counts the number of words...

    In csh, the variable '$*' has the command line (minus the actual command itself), so echo that variable into 'wc -w':

    #!/bin/csh

    echo "The number of command line arguments is"

    echo "$*" | wc -w
     
  4. Peter Yee

    Peter Yee Stunt Coordinator
    Supporter

    Joined:
    Aug 31, 1998
    Messages:
    105
    Likes Received:
    0
    Well, I checked on csh. '$#' evaluates to the number of command line arguments, so you won't have to call out of the shell to any other programs to count them.

    -Peter
     

Share This Page