10

Where am I going wrong?

I have some files as follows:

filename_tau.txt
filename_xhpl.txt
filename_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
3
  • bash script .. sorry i forgot to mention it Commented Nov 20, 2009 at 8:56
  • remember to put things like that into the tags, it makes the question easier to find for your target audience, ie. the people who have filtered out bash scripts as an interesting tag. Commented Nov 20, 2009 at 8:59
  • Please keep the code formated as code - it'll be a lot easier to understand. Commented Nov 20, 2009 at 9:02

5 Answers 5

14

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

As explained in the documentation this is a shorthand syntax, and this snippet is equivalent to:

for point in "$@"; do
  grep "$str" ${filename}${point}.txt 
done
Sign up to request clarification or add additional context in comments.

2 Comments

I suggest quotes around the filename argument to avoid trouble with spaces.
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.
7

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: ${!#}

1 Comment

Nice addition Dennis - just what I need now
4

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

Comments

2

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

Comments

0
args=$@;args=${args// /,}
grep "foo" $(eval echo file{$args})

Comments

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.