Advertisement

Linux Shell Scripts

Started by November 29, 2002 08:17 AM
5 comments, last by Evil Bill 22 years, 2 months ago
Hey all. We''ve been given this uni assignemnt which none of us have a clue about. I''ve already tried e-mailing the lecturer, but hes not replying. The task is: "Count the number of lines which contain all the words given in the command line." We''ve written C programs that we should us:
  • findword word - where "word" is the word to search for (basicly the same as grep)
  • countlines - count the number of lines in stdin The closest we have is:
    
    findword $1 | findword $2 < testfile.txt
     
    But obviously this only works for 2 arguments. We''ve also got:
    
    for i
    do
      findowrd $1 < testfile.txt
    done
     
    But this will print all the lines containing $1, followed by all the lines containing $2. What we need is some way to pipe the output of the previous loop to the input of the current loop. Any ideas?
  • Member of the Unban Mindwipe Society (UMWS)
    First off, which shell are you using? Are you required to use a certain shell? Or can you choose any that are available? If so, which ones can you choose from?
    Advertisement
    findword $1 < testfile.txt | findword $2 | findword $3 | ... | findword $n | countlines 
    quote: Original post by Oluseyi
    findword $1 < testfile.txt | findword $2 | findword $3 | ... | findword $n | countlines  

    Umm...I think that''s what he''s trying to avoid doing. I think he''s wanting to do this in a script that will support any number of words, so he can avoid hand coding it each time like you just did. If only it were that easy to type in "... | findword $n" or "findword $1 | etc." or "findword $1 | and so on..." and have the shell understand that, I don''t think he would have asked the question in the first place.

    Create the command as a string, something like (borrowing syntax and identifiers from Perl):
    $cmd = "findword " + $ARGV[1] + " < " + $ARGV[0];$i = 2while( $i != $ARGC ){  $cmd += (" | " + $ARGV[$i]);  ++$i;}$cmd += " | countline"; 

    Then execute the string using the backtick operator (`):
     `$cmd`; 

    Have a nice weekend.
    agreed with the above, although i personally would do

    eval $str

    rather than

    `$str`
    Advertisement
    Ahhh.... i never throught of doing that!
    Thats fantastic, i''ll give it a go on Monday

    Cheers!

    Member of the Unban Mindwipe Society (UMWS)

    This topic is closed to new replies.

    Advertisement