如何在shell中创建包含多个列的循环?

时间:2016-04-25 03:14:05

标签: linux shell awk

我有一个包含三列(ID号,x,y)的文件

ifile.txt
1      32.2    21.4
4      33.2    43.5
5      21.3    45.6
12     22.3    32.5
32     21.5    56.3
43     33.4    23.4
44     23.3    22.3
55     22.5    32.4

我想在第2列和第3列上进行循环,这样就像

一样
for x=32.2 and y=21.4; do execute a fortran program
for x=33.2 and y=43.5; do execute the same program
and so on

虽然我的以下脚本正在运行,但我需要它以有效的方式。

s1=1   #serial number
s2=$(wc -l < ifile.txt)   #total number to be loop
while [ $s1 -le $s2 ]
do
x=$(awk 'NR=='$s1' {print $2}' ifile.txt)
y=$(awk 'NR=='$s1' {print $3}' ifile.txt)
cat << EOF > myprog.f
...
take value of x and y
...
EOF
ifort myprog.f
./a.out
(( s1++ ))
done

请注意:myprog.f是在cat程序中编写的。例如,

cat << EOF > myprog.f
....
....
take value of x and y
....
....
EOF

2 个答案:

答案 0 :(得分:4)

在bash中读取文件的简单方法是

while read -r _ x y; do
    echo "x is $x, y is $y"
    # your Fortran code execution
done < ifile.txt
x is 32.2, y is 21.4
x is 33.2, y is 43.5
x is 21.3, y is 45.6
x is 22.3, y is 32.5
x is 21.5, y is 56.3
x is 33.4, y is 23.4
x is 23.3, y is 22.3
x is 22.5, y is 32.4

答案 1 :(得分:2)

看起来你正试图在每次循环迭代中创建Fortran源代码,循环变量被编入源代码,编译它,然后调用它,这是非常低效的。

相反,您应该创建一个Fortan程序一次,并让它接受参数
(我不知道Fortran,你还没有说明一个特定的编译器,但也许this GNU Fortran documentation会让你开始。)

假设您有这样的程序且其路径为./a.out,您可以按如下方式调用awkxargs,并传递第二个($2)和第三个({1}} $3)字段作为参数:

awk '{ print $2, $3 }' file | xargs -n 2 ./a.out
  • awk '{ print $2, $3 }'打印每个输入行的第二个和第三个以空格分隔的字段,用空格分隔。

  • xargs -n 2awk的输出中获取值对,并以每对作为参数调用./a.out。 (这种方法依赖于没有嵌入空格的值,这就是这种情况。)

相关问题