7

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:

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.

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.

2 Answers 2

14

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. Like:

while read field1 field2 field3 field4; do
  if [ -e "$field1" ]; then
     something
  elif [ -e "$field2" ]; then
      ...
  fi
done < file.txt
Sign up to request clarification or add additional context in comments.

2 Comments

Questioning the OPs motivation does not answer the question.
Interpreting the request, proposing an approach (line by line instead of word by word), and then providing a correct answer correctly literally counts as answering the question.
2

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 }'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.