tags:

views:

309

answers:

5

Where am I going wrong?

I have some files as follows:

filename_tau.txt
filename_xhpl.txt
fiename_fft.txt
filename_PMB_MPI.txt
filename_mpi_tile_io.txt

I pass tau, xhpl, fft, mpi_tile_io and PMB_MPI as positional parameters to script as follows:

./script.sh tau xhpl mpi_tile_io fft PMB_MPI

I want grep to search inside a loop, first searching tau, xhpl and so on..

point=$1     #initially points to first parameter
i="0"
while [$i -le 4]
do
  grep "$str" ${filename}${point}.txt
  i=$[$i+1]
  point=$i     #increment count to point to next positional parameter
done
A: 

See here, you need shift to step through positional parameters.

Alberto Zaccagni
+1  A: 

Set up your for loop like this. With this syntax, the loop iterates over the positional parameters, assigning each one to 'point' in turn.

for point; do
  grep "$str" ${filename}${point}.txt 
done
Steve K
I suggest quotes around the filename argument to avoid trouble with spaces.
Aaron Digulla
I think you're missing an assignment like `point="$@"`.
Dennis Williamson
Aaron, good point. I copy/pasted that line from the question without editing it. Dennis, that's not correct. There's no need to assign to point directly. See the "Compound Commands" section of the Bash manual for all the details.
Steve K
A: 

Try something like this:

# Iterating through the provided arguments
for ARG in $*; do
    if [ -f filename_$ARG.txt]; then
        grep "$str" filename_$ARG.txt 
    fi
done
Bobby
A: 
args=$@;args=${args// /,}
grep "foo" $(eval echo file{$args})
ghostdog74
+1  A: 

There is more than one way to do this and, while I would use shift, here's another for variety. It uses Bash's indirection feature:

#!/bin/bash
for ((i=1; i<=$#; i++))
do
    grep "$str" ${filename}${!i}.txt
done

One advantage to this method is that you could start and stop your loop anywhere. Assuming you've validated the range, you could do something like:

for ((i=2; i<=$# - 1; i++))

Also, if you want the last param: ${!#}

Dennis Williamson