linux - 在 shell 中循环多列

标签 linux shell loops unix awk

我有一个包含三列(身份证号、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

我想将 ID 号用作循环,这样读起来会像

when ID=1, then x=32.2, y=21.4
when ID=4, then x=33.2, y=43.5
and so on

我做了如下,但似乎很漫长。

id1=1   #ID number
id2=$(wc -l < ifile.txt)   #total number of IDs
while [ $id1 -le $id2 ]
do
ID=$(awk 'NR=='$id1' {print $1}' ifile.txt)
x=$(awk 'NR=='$id1' {print $2}' ifile.txt)
y=$(awk 'NR=='$id1' {print $3}' ifile.txt)
#
#here I want to do some computation using ID, x and y
#e.g. with each ID, I will execute a program by changing its corresponding x and y values
#for instance
echo $ID $x $y
(( id1++ ))
done

我需要缩短它和方便的方式。

最佳答案

这会读取每一行并对 x 和 y 进行计算(你没有说是什么计算,所以我编了一个):

$ awk '{printf "ID=%2s: x+y*y=%7.2f\n",$1,$2+$3*$3;}' ifile.txt 
ID= 1: x+y*y= 490.16
ID= 4: x+y*y=1925.45
ID= 5: x+y*y=2100.66
ID=12: x+y*y=1078.55
ID=32: x+y*y=3191.19
ID=43: x+y*y= 580.96
ID=44: x+y*y= 520.59
ID=55: x+y*y=1072.26

换句话说,awk 比 shell 有更好的数学支持。如果您想进行计算,请在 awk 中全部完成。

关于linux - 在 shell 中循环多列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32773700/

相关文章:

java - 在数组中插入数字

java - 当多个 SDK 时更改项目 SDK

linux - 显示 Linux 启动时运行的 bash 脚本中的内容

linux - Perl CMS for nginx - 带有模板、样式表和导航

windows - CMD变量替换参数

Php - 为不同的 CSS 循环

loops - 我如何检查我是否在 ADO 记录集的最后一条记录上?

java.awt.HeadlessException : No X11 DISPLAY variable was set error during maven build

linux - 将 stat 命令的输出与 shell 脚本中的整数变量进行比较

python - 通过 SSH 连接到服务器并退出 Python 脚本(在同一 shell 中)