2

I'm writing a script that will fold, sort and count text in a file. I need to design the program so that, if it is given multiple filenames on the command line, it processes each one separately, one after the other. I think I could write a loop but I don't know that much about those yet so if possible would like to try other options. Are there other options that I can add to this so more than one file name can be entered in the command line?

if test $# -lt 1 then echo "usage: $0 Enter at least one DNA filename" exit fi if test -r $* then fold -w3 $* | sort | uniq -c | sort -k1,1nr -k2 else
echo "usage: $* must be readable" exit fi

Nena

2 Answers 2

3

for loop will be appropriate here. The following form is used to iterate over positional arguments:

for f; do
   # do work here using "$f" as the current argument
done

This is equivalent to a more verbose version:

for f in "$@"; do
   # do work here using "$f" as the current argument
done
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Roman, I need to learn more about the "for" loop. Good answer.
1

You can use a while loop and shift to iterate through the command line arguments one by one as:

if test $# -lt 1  # insufficient arguments.
then
  echo "usage: $0 Enter at least one DNA filename"
  exit
fi

# loop through the argument on by one.
# till their number($#) becomes 0.
while test $# -gt 0  
do    
if test -r "$1"  # use $1..$* represent all arguments.
then
  fold -w3 "$1" | sort | uniq -c | sort -k1,1nr -k2
else
  echo "usage: $1 must be readable"
  exit
fi

# shift so that 2nd argument now comes in $1.
shift

done

1 Comment

That's a horribly complicated way, and it's missing double quotes around $1 throughout. @user475364: just go with Roman Cheplyaka's answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.