Scroll rows and multiple columns in bash

I am trying to loop in a file that has multiple rows with multiple columns (fields) with conditions.

Here is an example sample file ( file.txt ):

 aaa bbb ccc ddd kkk fff ggg hhh lll ooo sss 

... etc...

I want to write a bash script that intersects the first line of the first field, and if the name exists, then the second line continues. If the name of the first line of the first field does not exist, check the second field (in this case, check the name "bbb") and so on until the fourth. I have 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 checks both rows and columns. But I also had to go to the second, third and fourth fields, if the first field does not exist and if the second field does not exist, check the third field before the fourth.

+4
source share
1 answer

I think what you're really trying to do is read the file line by line, not word by word. You can do this with while and read . How:

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

Source: https://habr.com/ru/post/1433064/


All Articles