遍历 shell 中的结果集
Iterating through a result set in shell
所以我为此搜索了很多,我对 Shell 还很陌生,
我想遍历 SHELL 脚本中的结果集行,对于每一行,我想使用当前行的每一列执行一些代码。
让我们假设结果集是这样的。
Query Priority Size
---------------------------------------------------
this is a sentence to execute high 124400
this is another example low 15000000
...
那么我如何设法迭代这个结果集并将每一列存储到他自己的变量中呢?这是第一行的示例:
var1="this is a sentence to execute"
var2="high"
var3=124400
#repeat process for next line
您可以执行以下操作:
- 将数据提取到带分隔符的文件(例如 csv)中,如果可能,请避免使用 headers。如果您有 headers,请务必在阅读时排除它们。
- 从文件中读取数据到一个数组或一组变量中
像这样:
# using an array - works great if we have a variable number of columns
while IFS=, read -r -a row; do
# ${row[0]} => column1, ${row[1]} => column2 and so on
# process data
done < input.dat
# using variables - works great if we have a fixed set of variables
while IFS=, read -r column1 column2 column3; do
# process data
done < input.dat
所以我为此搜索了很多,我对 Shell 还很陌生, 我想遍历 SHELL 脚本中的结果集行,对于每一行,我想使用当前行的每一列执行一些代码。 让我们假设结果集是这样的。
Query Priority Size
---------------------------------------------------
this is a sentence to execute high 124400
this is another example low 15000000
...
那么我如何设法迭代这个结果集并将每一列存储到他自己的变量中呢?这是第一行的示例:
var1="this is a sentence to execute"
var2="high"
var3=124400
#repeat process for next line
您可以执行以下操作:
- 将数据提取到带分隔符的文件(例如 csv)中,如果可能,请避免使用 headers。如果您有 headers,请务必在阅读时排除它们。
- 从文件中读取数据到一个数组或一组变量中
像这样:
# using an array - works great if we have a variable number of columns
while IFS=, read -r -a row; do
# ${row[0]} => column1, ${row[1]} => column2 and so on
# process data
done < input.dat
# using variables - works great if we have a fixed set of variables
while IFS=, read -r column1 column2 column3; do
# process data
done < input.dat