This is a very similar question to 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[1]; set 2nd = $i[2]; set 3rd = $i[3]
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
sh
installed and doesn't have the basic text processing tools like per, awk, sed etc? What operating system are you using? – terdon Nov 21 '21 at 13:30awk
orperl
orsed
or any other tool more suitable to text parsing. If you [edit] your question and explain what the final objective is, we should be able to help. – terdon Nov 21 '21 at 13:43foreach i ( `cat file ` )
unrolls all the values as separate items, as each one is separated from the next by some form of whitespace. Right there, you've lost any representation of n fields per line – Chris Davies Nov 21 '21 at 16:32tcsh
" - but you then say "I can certainly usesh
. So you're not limited totcsh
and you can use a shell that's got decent flow control loops. Remember that your interactive shell need not be the one that runs shell scripts – Chris Davies Nov 21 '21 at 16:35