在 bash 中循环遍历行和多列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12326024/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Loop through rows and multiple columns in bash
提问by Yacob
I'm trying to do a loop on a file which has a number of rows with multiple columns (fields) with conditions.
我正在尝试对具有多列(字段)和条件的多行文件进行循环。
Here is what a sample file (file.txt) looks like:
示例文件 ( file.txt) 如下所示:
aaa bbb ccc
ddd kkk
fff ggg hhh lll
ooo
sss
...etc...
...等等...
I want to write a bash script that loops over first row of the first field and if the name exists then continues to the second row. If the name of the first row of the first field does not exist test then test the second field (in this case test the name "bbb") and so on until the fourth. I have a variable field numbers with a maximum of four(4) fields and a minimum of one field (column) for a given row.
我想编写一个 bash 脚本,循环遍历第一个字段的第一行,如果名称存在,则继续到第二行。如果第一个字段的第一行的名称不存在测试,则测试第二个字段(在这种情况下测试名称“bbb”),依此类推,直到第四个。对于给定的行,我有一个可变字段编号,最多有四(4)个字段,最少有一个字段(列)。
for i in cat file.txt; do
echo $i
if [ -e $i ]; then
echo "name exists"
else
echo "name does not exist"
fi
done
Obviously the above script tests both rows and columns. But I wanted also to loop through to the second, third and fourth fields if the first field does not exist and if the second field does not exist test the third field and until the fourth.
显然,上面的脚本测试了行和列。但我还想循环到第二、第三和第四个字段,如果第一个字段不存在,如果第二个字段不存在,则测试第三个字段,直到第四个字段。
回答by Grisha Levit
I think what you're really trying to do is read the file line by line instead of word by word. You can do this with whileand read. Like:
我认为您真正想做的是逐行而不是逐字阅读文件。你可以用while和来做到这一点read。喜欢:
while read field1 field2 field3 field4; do
if [ -e "$field1" ]; then
something
elif [ -e "$field2" ]; then
...
fi
done < file.txt

