bash文件读取,while循环
如果这个问题已经得到解答,我很抱歉,但由于我不确定问题到底是什么(在几种可能性中),所以我的搜索没有成功。
我想要做的是获取每个在文本文件中写为一行的标签号,对包含该标签的文件执行操作,并将结果输出到文件中。我所拥有的是这样的:
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
其中 fslstats 是一个输出数字的命令,good_PFC.txt 是一个测试文件,其中包含
123
125
132
FA_unc_stats.txt 中的输出是
123 0.221061 0.097268
问题是,终端正确输出“125 not a file”,但不执行任何操作132,我知道它恰好指向一个真实的文件。所以我相信我的 while 循环中的语法有问题,但我不知道是什么!我敢打赌这很愚蠢,但我就是想不通。谢谢!
预计到达时间: 通过在 good_PFC.txt 末尾添加换行符来修复现在的问题是,每当我到达新标签时,我都需要将换行符写入输出文件,但它不会这样做。我尝试
echo /n >> FA_unc_stats.txt
先添加,但它在自己的行上打印“/n”...我在换行命令上失败了!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您知道循环是否在最后一行运行吗?由于缺少换行符,Bash 可能会跳过最后一行。尝试在文件的最后一行添加换行符,看看是否可以解决问题。
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.
只需添加“echo $line”,您就会看到读取循环是否按您的预期工作。
Just add 'echo $line' and you will see if the read loop is working as you expect.
拆下第一根管子
Remove the first pipe with
尝试将 fslstsats 命令放在反引号中:
`
try putting the fslstsats commands in back ticks:
`