Problem with sed in for loop, would appreciate some help

Dear expert users,

I am having trouble with this for loop, where I am editing a design file, replacing the subject, session and another parameter in the template design file.

When implementing the for loop, it did not do what I wanted it to, for example editing to {2014}/CAT_Run0[5] instead of my hoped-for 2014/CAT_Run05 .

When I tried to run it line by line, replacing the first parameter (using $subj) worked fine (2013 -> 2014), but I got an error on the second (using $run), to me mysterious:
sed: -i may not be used with stdin

for subj in `cat subjlist.txt`
cd $subj
for run in `cat stimruns.txt`; do
		cd CAT_Run0$run.ica
		block=`cat block.txt`
		cp /Users/template.fsf .	
		sed -i '' "s|2013|$subj|g" template.fsf
		sed -i '' "s|CAT_Run01.ica|CAT_Run0{$run}.ica|g" template.fsf
		sed -i '' "s|Block_5|Block_{$block}|g" template.fsf
done
cd ..
done

Any clues here would be highly appreciated.

1/
The first thing I observed is that you're doing

for var in `cat filename`
do
  ...
done

instead of

while read line
do
  ...
done < filename

2/
Next I see that in the inner loop you are copying /Users/template.fsf in each run of the loop. I think you don't intend this?

3/
Can you please give us sample of what the file contains, expected output, shell you're working on....

  1. Thank you so much, that is immediately helpful! :slight_smile: Didn't know while loops in UNIX.
  2. The copying was intended, since I need a changed version of the template.fsf in each folder (which is then run later in the script). This is the only way I know so far of doing this.
  3. Yeah, the template.fsf is a text file generated by FSL specifying details of a fMRI analysis, and I'm hoping to edit it in the loop. The stimruns.txt file for each subject only contains a column vector of numbers I want to loop over within a folder of a subject, and the subjlist.txt a column vector of foldernames (subject folders) I want to loop over.

--- Post updated at 10:13 AM ---

Oh, it's bash shell :slight_smile:

On top of what balajesuri already said, I don't think {$run} will yield what you expect it to yield, but it also would not yield what you posted ( [5] ). I'd expect something like {5} , rather. Same for {$block} . And, if a {2014} is inserted, I'd guess it's taken as read from the input file, which would imply you need to remove the {} first before using the data. Sample input data would help...

Howsoever, guessing your data structures etc. from what I see in post #1, how far would (untested)

while read subj
  do    while read run
          do    TMP=CAT_Run0${run}.ica
                read block < ${subj}${TMP}block.txt
                sed "s|2013|${subj}|g; s|CAT_Run01.ica|${TMP}|g; s|Block_5|Block_${block}|g" /Users/template.fsf > ${subj}${TMP}template.fsf
          done < ${subj}/stimruns.txt
  done < subjlist.txt

get you?