Sample Header Ad - 728x90

loop through file by row in tcsh

2 votes
3 answers
5964 views
This is a very similar question to [How to loop over the lines of a file?](https://unix.stackexchange.com/questions/7011/how-to-loop-over-the-lines-of-a-file) . I have a file with rows with _n_ fields, separated by spaces. I want to loop through this file by row, and use the set the fields as variables, for use in calling information from a different file. So, for example, my file looks like this:
A B C
D E F
H I J
K L M
I'd like to loop thru each line and set the variables to be the fields: foreach i ( cat file ) set 1st = $i; set 2nd = $i; set 3rd = $i end Right now, my shell is using spaces to separate the fields, and this means I can't set the 3 variables in each row. Were I to echo each $i - I'd see this: A B C D .... I'd like to know how to control my loop by using only the new lines as the separators. Here's what I really want to achieve. I want to grep rows in file A which contain 3 different values, all of which appear as space separated elements in the rows of file B. My plan was to loop thru each line in file B, setting variables for each of the (space separated) elements in that row of B, and then make use of these 3 elements. And then repeat for the next row of B. But my loop fails because it doesn't see the rows in file B. It only sees ALL the space separated elements, with no recognition of their grouping into rows of 3 elements. I hope this isn't confusing
Asked by ZakS (315 rep)
Nov 21, 2021, 01:24 PM
Last activity: Apr 27, 2025, 01:08 PM