views:

61

answers:

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

+1  A: 

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
codaddict
Thanks codaddict. This worked great.
Koala
That's a horribly complicated way, and it's missing double quotes around `$1` throughout. @user475364: just go with [Roman Cheplyaka's answer](http://stackoverflow.com/questions/3930403/unix-script-to-process-multiple-file-names/3930534#3930534).
Gilles
+3  A: 

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
Roman Cheplyaka
Thank you Roman, I need to learn more about the "for" loop. Good answer.
Koala