简体   繁体   English

在 bash 中循环遍历行和多列

[英]Loop through rows and multiple columns in bash

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.我想编写一个 bash 脚本,循环遍历第一个字段的第一行,如果名称存在,则继续到第二行。 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.如果第一个字段的第一行的名称不存在测试,则测试第二个字段(在这种情况下测试名称“bbb”),依此类推,直到第四个。 I have a variable field numbers with a maximum of four(4) fields and a minimum of one field (column) for a given row.对于给定的行,我有一个可变字段编号,最多有四(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.但我还想循环到第二、第三和第四个字段,如果第一个字段不存在,如果第二个字段不存在,则测试第三个字段,直到第四个字段。

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 while and read .你可以用whileread来做到这一点。 Like:像:

while read field1 field2 field3 field4; do
  if [ -e "$field1" ]; then
     something
  elif [ -e "$field2" ]; then
      ...
  fi
done < file.txt

This work for me to read columns, I think it can apply for your case.这个作品适合我看专栏,我觉得可以适用于你的情况。

while read field1 field2 field3 field4; do
    echo $field1 $field2 $field3 $field4
done < file.txt | awk '{ print $1,$2,$3,$4 }'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM