开发者

bash file reading, while loop

开发者 https://www.devze.com 2023-04-09 12:37 出处:网络
I\'m sorry if this has been answered but since I\'m not positive what exactly is the problem (among several possibilities) I haven\'t been successful in my searches.

I'm sorry if this has been answered but since I'm not positive what exactly is the problem (among several possibilities) I haven't been successful in my searches.

What I want to do is take label numbers that are each written as a line in a text file, do things with files containting that label, and output the results to a file. What I have is this:

cat good_PFC.txt | while read line;
do  
 base_file=${line}_blah.nii.gz
 new_fa=${line}_fa_uncmasked.nii.gz
 new_tr=${line}_tr_uncmasked.nii.gz 

 if [ -e $base_file ]; then

  echo -n "$line " >> FA_unc_stats.txt
  fslstats $new_fa -M | tr '\n' ' ' >> FA_unc_stats.txt
  fslstats $new_fa -S | tr '\n' ' ' >> FA_unc_stats.txt     

 else
  echo $line "not a file"
 fi;
done

In which fslstats is a command that outputs numbers and good_PFC.txt is a test file containing

123
125
132

The output in FA_unc_stats.txt is

123 0.221061  0.097268

What's wrong is, the terminal correctly outputs "125 not a file", but does nothing with 132, which I know happens to point to a real file. So I believe something is wrong with the syntax in my while loop, but I don't know what! I bet it's something stupid but I just can't figure it out. Thanks!

ETA: Fixed by adding a newline to the end of good_PFC.txt Now the problem is I need a newline written to the output file whenever I get to a new label, but it doesn't do that. I tried adding

echo /n >> FA_unc_stats.txt

first, but it prints "/n" on it's own line... I fail at开发者_开发知识库 newline commands!


Do you know if the loop is being run on the last line at all? Bash may be skipping the last line due to a lack of a newline terminator. Try adding a newline to the last line in the file and see if that fixes the problem.


Just add 'echo $line' and you will see if the read loop is working as you expect.


Remove the first pipe with

while read line; do
  ...
done <good_PFC.txt


try putting the fslstsats commands in back ticks:

`fslstats $new_fa -M | tr '\n' ' ' >> FA_unc_stats.txt`
 `fslstats $new_fa -S | tr '\n' ' ' >> FA_unc_stats.txt

`

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号